1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::collections::HashMap;
use std::sync::RwLock;
use lazy_static::*;
use config::{Config, File, FileFormat};
use handlebars::Handlebars;
use serde_json::value::{Map, Value as Json};
use reqwest::Url;
use authorization::Authorization;
use ::log::*;
use chrono::{DateTime, Local};

pub mod comment_server;
pub mod log;
pub mod filters;
pub mod handlers;
pub mod models;

// initialize: application settings 
lazy_static!{
    // pull-in comments specific settings from Settings.toml 
    static ref SETTINGS: HashMap<String, String> = get_settings();
    static ref TEMPLATES: Handlebars<'static> = get_templates();
    static ref AUTHZN: RwLock<Authorization> = get_authorization();
    static ref SESSION_ID: RwLock<String> = RwLock::new( String::new() );
}

// Extract Todo Specific settings from Settings.toml
fn get_settings() -> HashMap<String, String> {
    let mut config = Config::default();
    config.merge(File::new("Settings", FileFormat::Toml)).unwrap();
    let settings = config.try_into::<HashMap<String, String>>().unwrap(); // Deserialize entire file contents
    settings
}

pub fn config(key: &str) -> String {
    SETTINGS.get(key).unwrap().to_string()
}

fn get_templates() -> Handlebars<'static> {
    let mut hb = Handlebars::new();
    hb.register_template_file("index_page", "./templates/index_page.hbs").unwrap();
    hb.register_template_file("comments_page", "./templates/comments_page.hbs").unwrap();
    hb.register_template_file("reply_page_partial", "./templates/reply_page_partial.hbs").unwrap();
    hb    
}
fn get_authorization() -> RwLock<Authorization> {
    let authzn = Authorization::load( &config("resource_permissions"), &config("user_roles") );
    RwLock::new(authzn)
}

fn set_session_id(sid: String) {
    info!("setting session id into lazy static.........{:?}", &sid);
    let mut session_id = SESSION_ID.write().unwrap();
    *session_id = sid;
}

fn get_session_id() -> String {
    let sid = SESSION_ID.read().unwrap();
    sid.to_string()
}

pub fn allows_add(cid: &str, res: &str, data: &Map<String, Json>) -> bool {
    allows("add", cid, res, data)
}
pub fn allows_view(cid: &str, res: &str, data: &Map<String, Json>) -> bool {
    allows("view", cid, res, data)
}
pub fn allows_edit(cid: &str, res: &str, data: &Map<String, Json>) -> bool {
    allows("edit", cid, res, data)
}
pub fn allows_delete(cid: &str, res: &str, data: &Map<String, Json>) -> bool {
    allows("delete", cid, res, data)
}

fn allows(op: &str, cid: &str, res: &str, data: &Map<String, Json>) -> bool {
    debug!("Authzn: op: {:?}, cid: {:?}, resource: {:?}.............", op, cid, res);
    // isolate read locks and write locks using blocks
    { // block for read lock 
        let authzn_r = AUTHZN.read().unwrap();
        if authzn_r.has_permissions_for(cid) {  // if permissions are readily available on user 'cid', get it
            return match op {
                "add" => authzn_r.allows_add(cid, res, data),
                "view" => authzn_r.allows_view(cid, res, data),
                "edit" => authzn_r.allows_edit(cid, res, data),
                "delete" => authzn_r.allows_delete(cid, res, data),
                _ => false
            }
        }
    }   // read lock is dropped here
    // write lock uses the function block itself as it happens to be a last lock in this function
    let mut authzn_w = AUTHZN.write().unwrap(); // if no permissions available for user, open lock in write mode
    authzn_w.set_permissions_for(cid); // let derive permissions from user's roles and cache it in hashmap for future references
    match op {
        "add" => authzn_w.allows_add(cid, res, data),
        "view" => authzn_w.allows_view(cid, res, data),
        "edit" => authzn_w.allows_edit(cid, res, data),
        "delete" => authzn_w.allows_delete(cid, res, data),
        _ => false
    }
}

pub fn render(template_name: &str, data: &Map<String, Json>) -> String {
    TEMPLATES.render(template_name, data)
        .unwrap_or_else(|err| err.to_string())
}

pub fn comments_url() -> Url {
    let ip = config("backend_server_ip_address");
    let path = config("backend_server_comments_path");
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    debug!("comments_url: {}", url);
    url
}
 
pub fn comments_total_url() -> Url {
    let ip = config("backend_server_ip_address");
    let path = config("backend_server_comments_total_path");
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    debug!("comments_total_url: {}", url);
    url
}

pub fn replies_url() -> Url {
    let ip = config("backend_server_ip_address");
    let path = config("backend_server_replies_path");
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    debug!("replies_url: {}", url);
    url
}

pub fn replies_url_with(addl_path: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_replies_path");
    if addl_path.len() > 0 {
        path = path.to_owned() + "/" + addl_path;
    }
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    debug!("replies_url_with: {}", url);
    url
}

pub fn session_url() -> Url {
    let ip = config("app_server_local_ip_address");
    let path = config("app_server_session_path");
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    info!("session_url: {}.................................................................", url);
    url
}

pub fn session_url_with(sid: &str) -> Url {
    let ip = config("app_server_local_ip_address");
    let mut path = config("app_server_session_path");
    if sid.len() > 0 {
        path = path.to_owned() + "/" + sid;
    }
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    info!("session_url: {}.................................................................", url);
    url
}

pub fn commenter_url_with(addl_path: &str) -> Url {
    let ip = config("app_server_local_ip_address");
    let mut path = config("app_server_commenter_path");
    if addl_path.len() > 0 {
        path = path.to_owned() + "/" + addl_path;
    }
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);    
    debug!("commenter_url_with: {}", url);
    url
}

pub fn avatar_url_path() -> String {
    let ip = config("app_server_named_ip_address");
    let path = config("app_server_avatar_path");
    ip + &path
}

pub fn status_update_url(status: &str, cid: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_comment_path");
    path = path.to_owned() + "/" + status + "/" + cid;
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("status_update_url: {}", url);
    url
}

pub fn comment_msg_update_url(cid: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_comment_message_path");
    path = path.to_owned() + "/" + cid;
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("comment_msg_update_url: {}", url);
    url
}

pub fn comments_trash_url(uid: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_comments_path");
    path = path.to_owned() + "/" + uid;
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("comments_trash_url: {}", url);
    url
}

pub fn reply_msg_update_url(cid: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_reply_message_path");
    path = path.to_owned() + "/" + cid;
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("reply_msg_update_url: {}", url);
    url
}

pub fn replies_trash_url(uid: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_replies_path");
    path = path.to_owned() + "/" + uid;
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("replies_trash_url: {}", url);
    url
}

pub fn more_comments_url(count: usize) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_more_comments_path");
    path = path.to_owned() + "/" + &count.to_string();
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("more_comments_url: {}", url);
    url   
}

pub fn upvote_url() -> Url {
    let ip = config("backend_server_ip_address");
    let path = config("backend_server_upvote_path");
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("upvote_url: {}", url);
    url       
}

pub fn upvotes_count_url(comment_id: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_upvotes_count_path");
    path = path.to_owned() + "/" + &comment_id;
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("upvotes_count_url: {}", url);
    url       
}

pub fn downvote_url() -> Url {
    let ip = config("backend_server_ip_address");
    let path = config("backend_server_downvote_path");
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("downvote_url: {}", url);
    url       
}

pub fn downvotes_count_url(comment_id: &str) -> Url {
    let ip = config("backend_server_ip_address");
    let mut path = config("backend_server_downvotes_count_path");
    path = path.to_owned() + "/" + &comment_id;
    let mut url = Url::parse(&ip).unwrap();
    url.set_path(&path);
    debug!("downvotes_count_url: {}", url);
    url       
}

pub fn time_ago(dt_str: &str) -> String {
    let dt = DateTime::parse_from_str(dt_str, "%Y-%m-%d %H:%M:%S%.9f %z").unwrap();
    let now = Local::now();
    let mut elapsed = now.timestamp_millis() - dt.timestamp_millis(); // subtract now from dt

    elapsed = elapsed / 1000; // convert from millis to seconds
    let mut plural = "";
    if elapsed > 1 { plural = "s" };
    if elapsed < 60 { return format!("{} second{} ago", &elapsed, plural); }

    elapsed = elapsed / 60; // convert to minutes
    plural = if elapsed == 1 { "" } else { "s" };
    if elapsed < 60 { return format!("{} minute{} ago", &elapsed, plural); }

    elapsed = elapsed / 60; // convert to hours
    plural = if elapsed == 1 { "" } else { "s" };
    if elapsed < 24 { return format!("{} hour{} ago", &elapsed, plural); }

    elapsed = elapsed / 24; // convert to days
    plural = if elapsed == 1 { "" } else { "s" };
    if elapsed < 7 { return format!("{} day{} ago", &elapsed, plural); }

    elapsed = elapsed / 7; // convert to weeks
    plural = if elapsed == 1 { "" } else { "s" };
    if elapsed <= 4 { return format!("{} week{} ago", &elapsed, plural); }

    let now_year = now.format("%Y").to_string();
    if dt_str.contains( &now_year ) { // check whether year now and commented year are same
        dt.format("%d %B").to_string()  // show dd MON format, if years are same
    } else {
        dt.format("%d %B %Y").to_string()  // show dd MON YYY format, if years are different
    }
}