PageRenderTime 67ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/gnowsys-ndf/gnowsys_ndf/ndf/views/analytics.py

https://gitlab.com/g66shivam/gstudio
Python | 1111 lines | 963 code | 101 blank | 47 comment | 39 complexity | b83f7a241ce26d2e363c696b91f4a4ab MD5 | raw file
  1. ''' -- Imports from python libraries -- '''
  2. import datetime
  3. import json
  4. import pymongo
  5. import re
  6. ''' -- imports from installed packages -- '''
  7. from django.http import HttpResponseRedirect, HttpResponse, Http404
  8. from django.shortcuts import render_to_response, redirect, render
  9. from django.template import RequestContext
  10. from django.template import TemplateDoesNotExist
  11. from django.template.loader import render_to_string
  12. from django.core.urlresolvers import reverse
  13. from django.contrib.auth.decorators import login_required
  14. from django.core.files.storage import get_valid_filename
  15. from django.core.files.move import file_move_safe
  16. from django.core.files.temp import gettempdir
  17. from django.core.files.uploadedfile import UploadedFile # django file handler
  18. from mongokit import paginator
  19. from gnowsys_ndf.ndf.org2any import org2html
  20. from gnowsys_ndf.ndf.models import *
  21. from pymongo import Connection
  22. try:
  23. from bson import ObjectId
  24. except ImportError: # old pymongo
  25. from pymongo.objectid import ObjectId
  26. from gnowsys_ndf.ndf.models import node_collection, triple_collection, gridfs_collection
  27. from gnowsys_ndf.ndf.views.methods import get_node_metadata, get_node_common_fields, set_all_urls # , get_page
  28. from gnowsys_ndf.ndf.views.methods import create_gattribute, get_group_name_id, get_execution_time
  29. benchmark_collection = db[Benchmark.collection_name]
  30. analytics_collection = db[Analytics.collection_name]
  31. ins_objectid = ObjectId()
  32. '''
  33. FUNCTION TO REGISTER CUSTOM ACTIVITIES USING AJAX
  34. '''
  35. @get_execution_time
  36. def custom_events(request):
  37. transaction = { 'status' : None, 'message' : None}
  38. analytics_event = analytics_collection.Analytics()
  39. analytics_event['user'] = request.user.username
  40. try :
  41. analytics_event['session_key'] = request.session.session_key
  42. except :
  43. transaction['status'] = 0
  44. transaction['message'] = 'Error retrieving the session key.'
  45. analytics_event['timestamp'] = datetime.datetime.now();
  46. try :
  47. analytics_event['group_id'] = Gid(request.POST['group_id'])
  48. analytics_event['action'] = json.loads(request.POST['action'])
  49. analytics_event['obj'][request.POST['obj']] = json.loads(request.POST['obj_properties'])
  50. except :
  51. transaction['status'] = 0
  52. transaction['message'] = 'Incomplete Data.'
  53. if transaction['status'] is None :
  54. analytics_event.save()
  55. transaction['status'] = 1
  56. transaction['message'] = 'Transaction Successful !'
  57. return HttpResponse(json.dumps(transaction))
  58. '''
  59. USER ANALYTICS VIEWS
  60. '''
  61. @get_execution_time
  62. def default_user(request,group_id):
  63. return redirect("/")
  64. @login_required
  65. @get_execution_time
  66. def user_list_activities(request,group_id):
  67. '''
  68. Lists the detailed activities of the user
  69. '''
  70. user = request.user.username
  71. query("user",{ "username" : request.user.username })
  72. cursor = analytics_collection.find({"user.name" : request.user.username}).sort("timestamp",-1)
  73. lst = []
  74. temp_date = datetime.date(1970, 1, 1)
  75. date_col = {}
  76. i=-1
  77. for doc in cursor :
  78. if temp_date != doc[u'timestamp'].date().strftime("%d %b, %Y") :
  79. temp_date = doc[u'timestamp'].date().strftime("%d %b, %Y")
  80. date_col = {}
  81. date_col[str(temp_date)] = []
  82. date_col[str(temp_date)].append(doc)
  83. lst.append(date_col)
  84. i=i+1
  85. else :
  86. lst[i][str(temp_date)].append(doc)
  87. pass
  88. return render (request, "ndf/analytics_list_details.html", { "user_name" : user, "data" : lst,"group_id" : group_id, "groupid" : group_id, "specific" : False})
  89. @login_required
  90. @get_execution_time
  91. def user_app_activities(request,group_id,part):
  92. '''
  93. Lists the detailed activities of the user
  94. '''
  95. user = request.user.username
  96. query("user",{ "username" : request.user.username })
  97. cursor = analytics_collection.find({"obj."+part : { "$exists" : True}, "action.key" : {"$in" : ['create', 'edit', 'add', 'delete']}, "user.name" : request.user.username}).sort("timestamp",-1)
  98. lst = []
  99. temp_date = datetime.date(1970, 1, 1)
  100. date_col = {}
  101. i=-1
  102. for doc in cursor :
  103. if temp_date != doc[u'timestamp'].date().strftime("%d %b, %Y") :
  104. temp_date = doc[u'timestamp'].date().strftime("%d %b, %Y")
  105. date_col = {}
  106. date_col[str(temp_date)] = []
  107. date_col[str(temp_date)].append(doc)
  108. lst.append(date_col)
  109. i=i+1
  110. else :
  111. lst[i][str(temp_date)].append(doc)
  112. pass
  113. return render (request, "ndf/analytics_list_details.html", { "user_name" : user, "data" : lst,"group_id" : group_id, "groupid" : group_id, "specific" : True, "app" : part})
  114. @get_execution_time
  115. def get_user_sessions(user) :
  116. '''
  117. Returns the user activities grouped by sessions
  118. '''
  119. cursor = analytics_collection.find({"user.name" : user}).sort("timestamp",-1)
  120. lst = []
  121. sessions_list =[]
  122. d={}
  123. i=-1
  124. for doc in cursor :
  125. sk = str(doc['session_key'])
  126. if i!=-1 and d['session_key']==sk :
  127. sessions_list[i]["start_date"] = doc['timestamp']
  128. sessions_list[i]["activities"] += 1
  129. sessions_list[i]["duration"] = sessions_list[i]["end_date"] - sessions_list[i]["start_date"]
  130. else :
  131. d= {}
  132. i+=1
  133. d["session_key"]=sk
  134. d["end_date"] = doc['timestamp']
  135. d["start_date"] = doc['timestamp']
  136. d["duration"] = d["end_date"] - d["start_date"]
  137. d["activities"] = 1
  138. d["user"] = doc['user']
  139. sessions_list.append(d)
  140. return sessions_list
  141. @login_required
  142. @get_execution_time
  143. def user_summary(request,group_id):
  144. '''
  145. Renders the summary of the User activities on the Metastudio
  146. '''
  147. query("user",{ "username" : request.user.username })
  148. session_info = get_user_sessions(request.user.username)
  149. data = {}
  150. data['num_of_sessions'] = len(session_info)
  151. data['latest_activity'] = session_info[0]['end_date']
  152. duration = datetime.timedelta(0, 0)
  153. data['total_activities'] = 0
  154. for session in session_info :
  155. duration += session['duration']
  156. data['total_activities'] += session['activities']
  157. data['avg_session_duration'] = duration/data['num_of_sessions']
  158. data['num_of_pages'] = analytics_collection.find({ "user.name" : request.user.username, "action.key" : "create", "obj.page" : { '$exists' : 'true'}}).count()
  159. data['num_of_files'] = analytics_collection.find({ "user.name" : request.user.username, "action.key" : "create", "obj.file" : { '$exists' : 'true'}}).count()
  160. data['num_of_forums_created'] = analytics_collection.find({ "user.name" : request.user.username, "action.key" : "create", "obj.forum" : { '$exists' : 'true'}}).count()
  161. data['num_of_threads_created'] = analytics_collection.find({ "user.name" : request.user.username, "action.key" : "create", "obj.thread" : { '$exists' : 'true'}}).count()
  162. data['num_of_replies'] = analytics_collection.find({ "user.name" : request.user.username, "action.key" : "add", "obj.reply" : { '$exists' : 'true'}}).count()
  163. data['num_of_tasks'] = analytics_collection.find({ "user.name" : request.user.username, "action.key" : "create", "obj.task" : { '$exists' : 'true'}}).count()
  164. # More statistics can be queried from the anlytics_collection and added here.
  165. return render (request, "ndf/analytics_summary.html",
  166. { "data" : data,"group_id" : group_id, "groupid" : group_id})
  167. @login_required
  168. @get_execution_time
  169. def user_graphs(request) :
  170. return render_to_response("ndf/analytics_user_graphs.html", {})
  171. '''
  172. GROUP ANALYTICS VIEWS
  173. '''
  174. @get_execution_time
  175. def default_group(request,group_id):
  176. return redirect('/'+group_id+'/analytics/group/summary')
  177. @login_required
  178. @get_execution_time
  179. def group_summary(request,group_id):
  180. '''
  181. Renders the summary of all the activities done by the members of the Group
  182. '''
  183. group_name, group_id = get_group_name_id(group_id)
  184. query("group",{ "group_id" : group_id })
  185. data = {}
  186. pipe = [{'$match' : { 'group_id' : str(group_id)}}, {'$group': {'_id': '$user.name', 'num_of_activities': {'$sum': 1}}}]
  187. sorted_list = analytics_collection.aggregate(pipeline=pipe)
  188. sorted_list_acc_activities = sorted(sorted_list['result'],key = lambda k:k[u'num_of_activities'],reverse=True)
  189. data['active_users'] = []
  190. i=0
  191. for doc in sorted_list_acc_activities :
  192. data['active_users'].append({ "name" : (doc[u'_id']) , "activities" : doc[u'num_of_activities'] } )
  193. i+=1
  194. if i==3:
  195. break
  196. Course = node_collection.find_one({"_type":"GSystemType","name":"Course"})
  197. CourseEventGroup = node_collection.find_one({"_type":"GSystemType","name":"CourseEventGroup"})
  198. TwistGst = node_collection.find_one({"_type":"GSystemType","name":"Twist"})
  199. data['forums'] = db['Nodes'].find({"url":"forum", "group_set":ObjectId(group_id)}).count()
  200. data['threads'] = db['Nodes'].find({"member_of":ObjectId(TwistGst._id),"group_set":ObjectId(group_id)}).count()
  201. regx=re.compile("^Reply of:.*")
  202. data['replies'] = db['Nodes'].find({"name": regx,"group_set":ObjectId(group_id)}).count()
  203. data['files'] = db['Nodes'].find({"url":"file", "group_set":ObjectId(group_id)}).count()
  204. data['pages'] = db['Nodes'].find({"url":"page", "group_set":ObjectId(group_id)}).count()
  205. data['total_activities'] = analytics_collection.find({ "group_id" : unicode(group_id)}).count()
  206. data['Courses'] = node_collection.find({"type_of":Course._id}).count()
  207. data['announce_courses'] = node_collection.find({"prior_node":ObjectId(group_id),"member_of":CourseEventGroup._id}).count()
  208. data['recent'] = {}
  209. specific_date = datetime.datetime.now() - datetime.timedelta(days=7)
  210. data['recent']['forums'] = analytics_collection.find({"action.key": {"$in" : ['create', 'edit']}, "group_id": str(group_id), "obj.forum" : { '$exists' : 'true'},"timestamp":{'$gte':specific_date}}).count()
  211. data['recent']['threads'] = analytics_collection.find({"action.key": {"$in" : ['create', 'edit']}, "group_id": str(group_id), "obj.thread" : { '$exists' : 'true'},"timestamp":{'$gte':specific_date}}).count()
  212. data['recent']['replies'] = analytics_collection.find({"action.key": {"$in" : ['add']}, "group_id": str(group_id), "obj.reply" : { '$exists' : 'true'},"timestamp":{'$gte':specific_date}}).count()
  213. data['recent']['files'] = analytics_collection.find({"action.key": {"$in" : ['create', 'edit']}, "group_id": str(group_id), "obj.file" : { '$exists' : 'true'},"timestamp":{'$gte':specific_date}}).count()
  214. data['recent']['pages'] = analytics_collection.find({"action.key": {"$in" : ['create', 'edit']}, "group_id": str(group_id), "obj.page" : { '$exists' : 'true'},"timestamp":{'$gte':specific_date}}).count()
  215. data['recent']['create_edit_course'] = analytics_collection.find({"action.key": {"$in" : ['create', 'edit']}, "group_id": str(group_id), "obj.course" : { '$exists' : 'true'},"timestamp":{'$gte':specific_date}}).count()
  216. return render (request ,"ndf/analytics_group_summary.html",
  217. { "data" : data, "group_id" : group_id, "groupid" : group_id})
  218. @login_required
  219. @get_execution_time
  220. def group_list_activities(request,group_id):
  221. '''
  222. Renders the list of activities of all the members of the group
  223. '''
  224. group_name, group_id = get_group_name_id(group_id)
  225. query("group",{ "group_id" : group_id })
  226. cursor = analytics_collection.find({"group_id" : str(group_id)}).sort("timestamp",-1)
  227. lst=[]
  228. i=-1
  229. temp_date = datetime.date(1970,1,1)
  230. date_col = {}
  231. for doc in cursor :
  232. if temp_date != doc[u'timestamp'].date().strftime("%d %b, %Y") :
  233. temp_date = doc[u'timestamp'].date().strftime("%d %b, %Y")
  234. date_col = {}
  235. date_col[str(temp_date)] = []
  236. date_col[str(temp_date)].append(doc)
  237. lst.append(date_col)
  238. i=i+1
  239. else :
  240. lst[i][str(temp_date)].append(doc)
  241. pass
  242. return render (request, "ndf/analytics_list_group_details.html",
  243. { "data" : lst, "group_id" : group_id, "groupid" : group_id, "group_name" : group_name})
  244. @login_required
  245. @get_execution_time
  246. def group_members(request, group_id) :
  247. '''
  248. Renders the list of members sorted on the basis of their contributions in the group
  249. '''
  250. group_name, group_id = get_group_name_id(group_id)
  251. query("group",{ "group_id" : group_id })
  252. '''
  253. grouping the data on the basis of user name
  254. '''
  255. pipe = [{'$match' : { 'group_id' : str(group_id)}}, {'$group': {'_id': '$user.name', 'num_of_activities': {'$sum': 1}}}]
  256. sorted_list = analytics_collection.aggregate(pipeline=pipe)
  257. sorted_list_acc_activities = sorted(sorted_list['result'],key = lambda k:k[u'num_of_activities'],reverse=True)
  258. computing_urls = [
  259. { 'key' : 'forums', 'url' : 'forum', 'status' : 'DRAFT' },
  260. { 'key' : 'threads', 'url' : 'forum/thread', 'status' : 'DRAFT' },
  261. { 'key' : 'files', 'url' : 'file', 'status' : 'PUBLISHED' },
  262. { 'key' : 'pages', 'url' : 'page', 'status' : 'PUBLISHED' },
  263. { 'key' : 'tasks', 'url' : 'task', 'status' : 'DRAFT' },
  264. { 'key' : 'replies', 'name' : re.compile("^Reply of:.*"), 'status' : 'DRAFT' }
  265. ]
  266. list_of_members = []
  267. for member in sorted_list_acc_activities :
  268. #try :
  269. member_doc = {}
  270. member_doc['count'] = member[u'num_of_activities']
  271. author = node_collection.find_one({ "_type" : "Author" , "name" : member[u'_id']})
  272. member_doc['name'] = member[u'_id']
  273. try :
  274. member_doc['email'] = author[u'email']
  275. except :
  276. pass
  277. for entity in computing_urls :
  278. member_doc[entity['key']] = 0
  279. if entity['key'] == 'replies' :
  280. try :
  281. nodes = node_collection.find({"name":entity['name'], "group_set":ObjectId(group_id), "created_by" : author[u'created_by'], "status": entity[u'status']}).count()
  282. member_doc[entity['key']] = nodes
  283. except :
  284. pass
  285. else :
  286. try :
  287. nodes = node_collection.find({"url":entity['url'], "group_set":ObjectId(group_id), "created_by" : author[u'created_by'], "status": entity[u'status']}).count()
  288. member_doc[entity['key']] = nodes
  289. except :
  290. pass
  291. list_of_members.append(member_doc)
  292. #except :
  293. # return HttpResponse('Fatal Error')
  294. return render (request, "ndf/analytics_group_members.html",
  295. {"data" : list_of_members ,"group_id" : group_id, "groupid" : group_id})
  296. @login_required
  297. @get_execution_time
  298. def group_member_info_details(request, group_id, user) :
  299. group_name, group_id = get_group_name_id(group_id)
  300. user_name = user
  301. try :
  302. cursor = analytics_collection.find({"group_id" : str(group_id), "user.name" : user}).sort("timestamp", -1)
  303. if(cursor.count() != 0) :
  304. data = {}
  305. data['activities'] = []
  306. data['activities']=[]
  307. i=-1
  308. temp_date = datetime.date(1970,1,1)
  309. date_col = {}
  310. for doc in cursor :
  311. if temp_date != doc[u'timestamp'].date().strftime("%d %b, %Y") :
  312. temp_date = doc[u'timestamp'].date().strftime("%d %b, %Y")
  313. date_col = {}
  314. date_col[str(temp_date)] = []
  315. date_col[str(temp_date)].append(doc)
  316. data['activities'].append(date_col)
  317. i=i+1
  318. else :
  319. data['activities'][i][str(temp_date)].append(doc)
  320. pass
  321. return render(request, "ndf/analytics_group_member_info.html",
  322. {"data" : data , "group_id" : group_id, "groupid" : group_id, "group_name" : group_name, "user_name" : user_name})
  323. except :
  324. return HttpResponse("fatal error")
  325. '''
  326. ANALYTICS PROCESSING
  327. '''
  328. @get_execution_time
  329. def query(analytics_type,details) :
  330. '''
  331. This function checks the Analytics data(for a user) in analytics_collection and gets the time to which the query set is updated.
  332. Based on the time, it fetches raw data from Benchmark collection and hands over to normalize to do the filtering and
  333. redundancy check.
  334. In case, the analytics_type is 'group', the function resolves the members of the group and calls itself recursively for each user,
  335. to update the analytics_collection.
  336. '''
  337. if analytics_type == "user" :
  338. cursor = analytics_collection.find({"user.name" : str(details['username']) }).sort("timestamp",-1).limit(1)
  339. latest_timestamp = datetime.datetime(1900,1,1)
  340. if cursor is None :
  341. pass
  342. else :
  343. for doc in cursor :
  344. latest_timestamp = doc['timestamp']
  345. break
  346. raw_data = benchmark_collection.find({"user" : details['username'], "last_update": {"$gt":latest_timestamp}}).sort("last_update",-1)
  347. if raw_data is None:
  348. pass
  349. else :
  350. normalize(raw_data)
  351. else :
  352. group_id = details['group_id']
  353. group_node = node_collection.find_one({"_id" : ObjectId(group_id)})
  354. if group_node is not None :
  355. member_list = group_node[u'author_set'] + group_node[u'group_admin']
  356. for member in member_list :
  357. author = node_collection.find_one({"_type" : "Author", "created_by" : int(member)})
  358. if author is not None :
  359. query("user",{"username" : author[u'name'] })
  360. return 1
  361. @get_execution_time
  362. def normalize(cursor) :
  363. '''
  364. Normailizes the raw data from Benchmark collection so as to filter irrelevent content -
  365. * filtering_list is the list of unwanted actions that gets filtered out
  366. * for documents having the same structure, only one is taken to remove redundancy
  367. Based on the GAPP name, the document is passed to functions in 'gapp_list' for further analysis
  368. '''
  369. cursor = cursor.sort("last_update",1)
  370. def gapp_list(gapp):
  371. return {
  372. "page": page_activity,
  373. "file": file_activity,
  374. "course": course_activity,
  375. "forum": forum_activity,
  376. "task": task_activity,
  377. "event": event_activity,
  378. "dashboard": dashbard_activity,
  379. "group": group_activity,
  380. }.get(gapp,default_activity)
  381. filtering_list = ["file/thumbnail",'None','',"home", "image/get_mid_size_img"]
  382. temp_doc = { u"calling_url" : None , u'last_update' : datetime.datetime(1900, 1, 1, 11, 19, 54)}
  383. for doc in cursor :
  384. if 'ajax' in str(doc[u'action']) or str(doc[u'action']) in filtering_list :
  385. pass
  386. else :
  387. if temp_doc[u'calling_url'] == doc[u'calling_url'] and temp_doc[u'session_key'] == doc[u'session_key'] and (doc[u'last_update'] - temp_doc[u'last_update'] < datetime.timedelta(0,300)):
  388. if u'has_data' in doc.keys() and bool(doc[u'has_data']) == 1 :
  389. if doc[u'has_data']["POST"] == True :
  390. temp_doc = doc
  391. elif doc[u'has_data']["GET"] == True :
  392. temp_doc = doc
  393. else :
  394. temp_doc[u'last_update'] = doc[u'last_update']
  395. else :
  396. temp_doc = doc
  397. else :
  398. if temp_doc[u'calling_url'] != None :
  399. url = str(temp_doc[u'calling_url']).split("/")
  400. group_id = Gid(url[1])
  401. gapp = url[2]
  402. gapp_list(gapp)(group_id,url,temp_doc)
  403. temp_doc = doc
  404. if temp_doc[u'calling_url'] != None :
  405. url = str(temp_doc[u'calling_url']).split("/")
  406. group_id = Gid(url[1])
  407. gapp = url[2]
  408. gapp_list(gapp)(group_id,url,temp_doc)
  409. return 1
  410. '''
  411. ANALYSIS OF ACTIVITIES BY INDIVIDUAL GAPPS
  412. '''
  413. @get_execution_time
  414. def initialize_analytics_obj(doc, group_id, obj) :
  415. '''
  416. Returns a new initialized object of the Analytics class
  417. '''
  418. analytics_doc=analytics_collection.Analytics()
  419. analytics_doc.timestamp=doc[u'last_update']
  420. author = db['Nodes'].find_one({"_type" : "Author", "name" : doc[u'user']})
  421. analytics_doc.user = { "name" : author[u'name'] , "id" : author[u'created_by']}
  422. analytics_doc.session_key = doc[u'session_key']
  423. analytics_doc.group_id = group_id
  424. analytics_doc.obj = { obj : { 'id' : None} }
  425. return analytics_doc
  426. @get_execution_time
  427. def page_activity(group_id,url,doc):
  428. '''
  429. This function updates the Analytic_col database with the new activities done on the
  430. page of MetaStudio, and also to see whether the page is published,deleted we
  431. check the status in the Nodes collection of database.
  432. And also we are assuming here that if the difference between the last update and created at
  433. is less than 5 seconds then we should have created the page else we must have viewed the page.
  434. '''
  435. analytics_doc = initialize_analytics_obj(doc, group_id, 'page')
  436. if url[3] == "delete":
  437. if ins_objectid.is_valid(url[4]) is True:
  438. n = node_collection.find_one({"_id":ObjectId(url[4])})
  439. if n['status']=="HIDDEN" or n['status']=="DELETED":
  440. analytics_doc.action = { 'key' : 'delete', "phrase" : "deleted a" }
  441. analytics_doc.obj['page']['id'] = url[4]
  442. analytics_doc.obj['page']['name'] = n[u'name']
  443. analytics_doc.obj['page']['url'] = n[u'url']
  444. analytics_doc.save()
  445. return 1
  446. elif url[3] == "page_publish" :
  447. if ins_objectid.is_valid(url[4]) is True:
  448. n=node_collection.find_one({"_id":ObjectId(url[4])})
  449. if n['status']=="PUBLISHED" :
  450. analytics_doc.action = { 'key' : 'publish', "phrase" : "published a" }
  451. analytics_doc.obj['page']['id'] = url[4]
  452. analytics_doc.obj['page']['name'] = n[u'name']
  453. analytics_doc.obj['page']['url'] = n[u'url']
  454. analytics_doc.save()
  455. return 1
  456. elif url[3] =="edit" :
  457. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  458. n=node_collection.find_one({"_id":ObjectId(url[4])})
  459. analytics_doc.action = { 'key' : 'edit' , "phrase" : "edited a" }
  460. analytics_doc.obj['page']['id'] = url[4]
  461. analytics_doc.obj['page']['name'] = n[u'name']
  462. analytics_doc.obj['page']['url'] = n[u'url']
  463. analytics_doc.save()
  464. return 1
  465. else:
  466. try :
  467. n = node_collection.find_one({"_id":ObjectId(url[3])})
  468. author_id = n[u'created_by']
  469. auth=node_collection.find_one({"_type": "Author", "created_by": author_id})
  470. if auth[u'name']==doc[u'user']:
  471. if (doc[u'last_update'] - n[u'created_at']).seconds < 5 :
  472. analytics_doc.action = { "key" : "create" , "phrase" : "created a" }
  473. analytics_doc.obj['page']['id'] = ObjectId(url[3])
  474. analytics_doc.obj['page']['name'] = n[u'name']
  475. analytics_doc.obj['page']['url'] = n[u'url']
  476. analytics_doc.save()
  477. return 1
  478. else :
  479. analytics_doc.action = { 'key' : "view" , "phrase" : "viewed a" }
  480. analytics_doc.obj['page']['id'] = ObjectId(url[3])
  481. analytics_doc.obj['page']['name'] = n[u'name']
  482. analytics_doc.obj['page']['url'] = n[u'url']
  483. analytics_doc.save()
  484. return 1
  485. else :
  486. analytics_doc.action = { 'key' : "view" , "phrase" : "viewed a" }
  487. analytics_doc.obj['page']['id'] = ObjectId(url[3])
  488. analytics_doc.obj['page']['name'] = n[u'name']
  489. analytics_doc.obj['page']['url'] = n[u'url']
  490. analytics_doc.save()
  491. return 1
  492. except Exception :
  493. pass
  494. return 0
  495. @get_execution_time
  496. def course_activity(group_id,url,doc):
  497. '''
  498. This function updates the analytics_collection database with the new activities done on the
  499. courses of MetaStudio, and also to see whether the course is created, edited or viewed.We
  500. check the status in the Nodes collection of database.
  501. And also we are assuming here that if the difference between the last update and created at
  502. is less than 5 seconds then we should have created the course.
  503. '''
  504. analytics_doc = initialize_analytics_obj(doc, group_id, 'course')
  505. if(url[3]=="create"):
  506. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  507. try :
  508. author = node_collection.find_one({'_type' : 'Author','name' : doc[u'user']})
  509. cursor = node_collection.find({'url' : 'course','created_by' : author[u'created_by']})
  510. for course_created in cursor :
  511. if (doc[u'last_update'] - course_created[u'created_at']).seconds < 5 :
  512. analytics_doc.action = { 'key' : 'create', 'phrase' : 'created a'}
  513. analytics_doc.obj['course']['id'] = ObjectId(course_created[u'_id'])
  514. analytics_doc.obj['course']['name'] = str(course_created[u"name"])
  515. analytics_doc.obj['course']['url'] = course_created[u'url']
  516. analytics_doc.save()
  517. except :
  518. return 0
  519. elif(url[3]=="course_detail"):
  520. if(ins_objectid.is_valid(url[4])):
  521. n=node_collection.find_one({"_id":ObjectId(url[4])})
  522. try :
  523. analytics_doc.action = { 'key' : 'view', 'phrase' : 'viewed a'}
  524. analytics_doc.obj['course']['id'] = ObjectId(url[4])
  525. analytics_doc.obj['course']['name'] = str(n[u"name"])
  526. analytics_doc.obj['course']['url'] = course_created[u'url']
  527. analytics_doc.save()
  528. except Exception :
  529. return 0
  530. elif(url[3]=="edit") :
  531. if(ins_objectid.is_valid(url[4])):
  532. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  533. n=node_collection.find_one({"_id":ObjectId(url[4])})
  534. try :
  535. analytics_doc.action = { 'key' : 'edit', 'phrase' : 'edited a'}
  536. analytics_doc.obj['course']['id'] = ObjectId(url[4])
  537. analytics_doc.obj['course']['name'] = str(n[u"name"])
  538. analytics_doc.obj['course']['url'] = course_created[u'url']
  539. analytics_doc.save()
  540. except Exception :
  541. return 0
  542. elif(ins_objectid.is_valid(url[3])):
  543. n=node_collection.find_one({"_id":ObjectId(url[3])})
  544. try :
  545. analytics_doc.action = { 'key' : 'view', 'phrase' : 'viewed a'}
  546. analytics_doc.obj['course']['id'] = ObjectId(url[4])
  547. analytics_doc.obj['course']['name'] = str(n[u"name"])
  548. analytics_doc.obj['course']['url'] = n[u'url']
  549. analytics_doc.save()
  550. except Exception :
  551. return 0
  552. return 1
  553. @get_execution_time
  554. def file_activity(group_id,url,doc):
  555. '''
  556. This function updates the analytics_collection database with the new activities done on the
  557. files of MetaStudio, and also to see whether the file is viewed,edited, deleted, uploaded .
  558. We check the status in the Nodes collection of database.
  559. And also we are assuming here that if the difference between the last update and created at
  560. is less than 5 seconds then we should have uploaded the file.
  561. '''
  562. analytics_doc = initialize_analytics_obj(doc, group_id, 'file')
  563. if(url[3]=="submit"):
  564. try :
  565. author = node_collection.find_one({'_type' : 'Author','name' : doc[u'user']})
  566. cursor = node_collection.find({'url' : 'file','created_by' : author[u'created_by']})
  567. for file_created in cursor :
  568. if (doc[u'last_update'] - file_created[u'created_at']).seconds < 5 :
  569. analytics_doc.action = { 'key' : 'create', 'phrase' : 'created a'}
  570. analytics_doc.obj['file']['id'] = ObjectId(file_created[u'_id'])
  571. analytics_doc.obj['file']['type'] = str(file_created[u"mime_type"])
  572. analytics_doc.obj['file']['name'] = str(file_created[u"name"])
  573. analytics_doc.obj['file']['url'] = file_created[u'url']
  574. analytics_doc.save()
  575. except :
  576. return 0
  577. elif(url[3]=="readDoc"):
  578. n=node_collection.find_one({"_id":ObjectId(url[4])})
  579. try :
  580. analytics_doc.action = { 'key' : 'download', 'phrase' : 'downloaded a'}
  581. analytics_doc.obj['file']['id'] = ObjectId(url[4])
  582. analytics_doc.obj['file']['type'] = str(n[u"mime_type"])
  583. analytics_doc.obj['file']['name'] = str(n[u"name"])
  584. analytics_doc.obj['file']['url'] = n[u'url']
  585. analytics_doc.save()
  586. except Exception :
  587. return 0
  588. elif url[3]=="details":
  589. if(ins_objectid.is_valid(url[4])):
  590. n=node_collection.find_one({"_id":ObjectId(url[4])})
  591. try :
  592. analytics_doc.action = { 'key' : 'view', 'phrase' : 'viewed a'}
  593. analytics_doc.obj['file']['id'] = ObjectId(url[4])
  594. analytics_doc.obj['file']['type'] = str(n[u"mime_type"])
  595. analytics_doc.obj['file']['name'] = str(n[u"name"])
  596. analytics_doc.obj['file']['url'] = n[u'url']
  597. analytics_doc.save()
  598. except Exception :
  599. return 0
  600. elif(ins_objectid.is_valid(url[3])):
  601. n=node_collection.find_one({"_id":ObjectId(url[3])})
  602. try :
  603. analytics_doc.action = { 'key' : 'view', 'phrase' : 'viewed a'}
  604. analytics_doc.obj['file']['id'] = ObjectId(url[4])
  605. analytics_doc.obj['file']['type'] = str(n[u"mime_type"])
  606. analytics_doc.obj['file']['name'] = str(n[u"name"])
  607. analytics_doc.obj['file']['url'] = n[u'url']
  608. analytics_doc.save()
  609. except Exception :
  610. return 0
  611. elif(url[3]=="delete"):
  612. if ins_objectid.is_valid(url[4]) is True:
  613. n=node_collection.find_one({"_id":ObjectId(url[4])})
  614. if n['status']=="HIDDEN" or n['status']=="DELETED":
  615. analytics_doc.action = { 'key' : 'delete', 'phrase' : 'deleted a'}
  616. analytics_doc.obj['file']['id'] = ObjectId(url[4])
  617. analytics_doc.obj['file']['type'] = str(n[u"mime_type"])
  618. analytics_doc.obj['file']['name'] = str(n[u"name"])
  619. analytics_doc.obj['file']['url'] = n[u'url']
  620. analytics_doc.save()
  621. elif(url[3]=="edit" or url[3]=="edit_file"):
  622. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  623. if ins_objectid.is_valid(url[4]) is True:
  624. n=node_collection.find_one({"_id":ObjectId(url[4])})
  625. analytics_doc.action = { 'key' : 'edit', 'phrase' : 'edited'}
  626. analytics_doc.obj['file']['id'] = str(url[4])
  627. analytics_doc.obj['file']['type'] = str(n[u"mime_type"])
  628. analytics_doc.obj['file']['name'] = str(n[u"name"])
  629. analytics_doc.obj['file']['url'] = n[u'url']
  630. analytics_doc.save()
  631. return 1
  632. @get_execution_time
  633. def forum_activity(group_id,url,doc):
  634. '''
  635. The function analyzes the forum activities of the user.
  636. It takes in the raw normalized document from the normalize() function and analyzes the doc for activities like create, delete, view forums, thread, reply etc.
  637. The analyzed data is stored in the Analytics collection.
  638. '''
  639. if ins_objectid.is_valid(url[3]) is False:
  640. if(url[3]=="delete"):
  641. if ins_objectid.is_valid(url[4]) is True:
  642. n=node_collection.find_one({"_id":ObjectId(url[4])})
  643. if n['status']=="HIDDEN" or n['status']=="DELETED":
  644. analytics_doc = initialize_analytics_obj(doc, group_id, 'forum')
  645. analytics_doc.action = { 'key' : 'delete', 'phrase' : 'deleted a' }
  646. analytics_doc.obj['forum']['id'] = url[4];
  647. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[4])})
  648. analytics_doc.obj['forum']['name'] = forum_node[u'name']
  649. analytics_doc.obj['forum']['url'] = forum_node[u'url']
  650. analytics_doc.save();
  651. return 1
  652. elif url[4]=="thread":
  653. if ins_objectid.is_valid(url[6]) is True:
  654. n=node_collection.find_one({"_id":ObjectId(url[6])})
  655. if n['status']=="HIDDEN" or n['status']=="DELETED":
  656. analytics_doc = initialize_analytics_obj(doc, group_id, 'thread')
  657. analytics_doc.action = { 'key' : 'delete', 'phrase' : 'deleted a' }
  658. analytics_doc.action[2] = 'thread'
  659. analytics_doc.args['thread']['id'] = ObjectId(url[6]);
  660. thread_node = db['Nodes'].find_one({ "_id" : ObjectId(url[6])})
  661. analytics_doc.obj['thread']['name'] = thread_node[u'name']
  662. analytics_doc.obj['forum']['url'] = thread_node[u'url']
  663. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[5])})
  664. analytics_doc.obj['thread']['forum'] = { "id" : forum_node[u'_id'], "name" : forum_node[u'name'], "url" : forum_node[u'url']};
  665. analytics_doc.save();
  666. return 1
  667. elif url[4]=="reply":
  668. if ins_objectid.is_valid(url[7]) is True:
  669. n=node_collection.find_one({"_id":ObjectId(url[7])})
  670. if n['status']=="HIDDEN" or n['status']=="DELETED":
  671. analytics_doc = initialize_analytics_obj(doc, group_id, 'reply')
  672. analytics_doc.action = { 'key' : 'delete', 'phrase' : 'deleted a' }
  673. analytics_doc.obj['reply']['id'] = url[7];
  674. reply_node = db['Nodes'].find_one({ "_id" : ObjectId(url[7])})
  675. analytics_doc.obj['reply']['name'] = reply_node[u'name'];
  676. analytics_doc.obj['reply']['url'] = reply_node[u'url']
  677. thread_node = db['Nodes'].find_one({ "_id" : ObjectId(url[6])})
  678. analytics_doc.obj['reply']['thread'] = { "id" : thread_node[u'_id'], "name" : thread_node[u'name'], "url" : thread_node[u'url']};
  679. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[5])})
  680. analytics_doc.obj['reply']['forum'] = { "id" : forum_node[u'_id'], "name" : forum_node[u'name'], "url" : forum_node[u'url']};
  681. analytics_doc.save();
  682. return 1
  683. elif url[3]=="thread" :
  684. try :
  685. if ins_objectid.is_valid(url[4]) is True:
  686. analytics_doc = initialize_analytics_obj(doc, group_id, 'thread')
  687. analytics_doc.action = { 'key' : 'view', 'phrase' : 'viewed a' }
  688. analytics_doc.obj['thread']['id'] = ObjectId(url[4]);
  689. thread_node = db['Nodes'].find_one({ "_id" : ObjectId(url[4])})
  690. analytics_doc.obj['thread']['name'] = thread_node[u'name'];
  691. analytics_doc.obj['thread']['url'] = thread_node[u'url'];
  692. analytics_doc.save();
  693. return 1
  694. except :
  695. pass
  696. elif url[3]=="edit_forum" :
  697. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  698. analytics_doc = initialize_analytics_obj(doc, group_id, 'forum')
  699. analytics_doc.action = { 'key' : 'edit', 'phrase' : 'edited a' }
  700. analytics_doc.obj['forum']['id'] = ObjectId(url[4]);
  701. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[4])})
  702. analytics_doc.obj['forum']['name'] = forum_node[u'name'];
  703. analytics_doc.obj['forum']['url'] = forum_node[u'url'];
  704. analytics_doc.save();
  705. return 1
  706. elif url[3]=="edit_thread" :
  707. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  708. analytics_doc = initialize_analytics_obj(doc, group_id, 'thread')
  709. analytics_doc.action = { 'key' : 'edit', 'phrase' : 'edited a' }
  710. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[4])})
  711. analytics_doc.obj['thread']['forum'] = { "id" : forum_node[u'_id'], "name" : forum_node[u'name'], "url" : forum_node[u'url']};
  712. analytics_doc.obj['thread']['id'] = ObjectId(url[5]);
  713. thread_node = db['Nodes'].find_one({ "_id" : ObjectId(url[5])})
  714. analytics_doc.obj['thread']['name'] = thread_node[u'name'];
  715. analytics_doc.obj['thread']['url'] = thread_node[u'url'];
  716. analytics_doc.save();
  717. return 1
  718. elif url[3] == 'add_node' :
  719. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  720. analytics_doc = initialize_analytics_obj(doc, group_id, 'reply')
  721. analytics_doc.action = { 'key' : 'add', 'phrase' : 'added a' }
  722. analytics_doc.save();
  723. return 1
  724. else:
  725. n=node_collection.find_one({"_id":ObjectId(url[3])})
  726. try :
  727. if url[4] == 'thread' :
  728. if url[5] == 'create' :
  729. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  730. try :
  731. author = node_collection.find_one({"_type" : "Author", "name" : doc[u'user']})
  732. except :
  733. pass
  734. if author :
  735. try :
  736. threads = node_collection.find({"url" : "forum/thread" , "created_by" : author[u'created_by']})
  737. for created_thread in threads :
  738. if (doc[u'last_update'] - created_thread[u'created_at']).seconds < 5 :
  739. analytics_doc = initialize_analytics_obj(doc, group_id, 'thread')
  740. analytics_doc.action = { 'key' : 'create', 'phrase' : 'created a' }
  741. analytics_doc.obj['thread']['id'] = str(created_thread[u'_id']);
  742. thread_node = db['Nodes'].find_one({ "_id" : created_thread[u'_id']})
  743. analytics_doc.obj['thread']['name'] = thread_node[u'name'];
  744. analytics_doc.obj['thread']['url'] = thread_node[u'url'];
  745. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[3])})
  746. analytics_doc.obj['thread']['forum'] = { "id" : forum_node[u'_id'], "name" : forum_node[u'name'], "url" : forum_node[u'url']};
  747. analytics_doc.save();
  748. return 1
  749. except :
  750. pass
  751. except :
  752. author_id=n[u'created_by']
  753. auth=node_collection.find_one({"_type": "Author", "created_by": author_id})
  754. if auth:
  755. if auth[u'name'] == doc[u'user']:
  756. created_at = n[u'created_at']
  757. if (doc[u'last_update'] - created_at).seconds < 5 :
  758. analytics_doc = initialize_analytics_obj(doc, group_id, 'forum')
  759. analytics_doc.action = { 'key' : 'create', 'phrase' : 'created a' }
  760. analytics_doc.obj['forum']['id'] = ObjectId(url[3]);
  761. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[3])})
  762. analytics_doc.obj['forum']['name'] = forum_node[u'name'];
  763. analytics_doc.obj['forum']['url'] = forum_node[u'url'];
  764. analytics_doc.save();
  765. return 1
  766. else :
  767. analytics_doc = initialize_analytics_obj(doc, group_id, 'forum')
  768. analytics_doc.action = { 'key' : 'view', 'phrase' : 'viewed a' }
  769. analytics_doc.obj['forum']['id'] = ObjectId(url[3]);
  770. forum_node = db['Nodes'].find_one({ "_id" : ObjectId(url[3])})
  771. analytics_doc.obj['forum']['name'] = forum_node[u'name'];
  772. analytics_doc.obj['forum']['url'] = forum_node[u'url'];
  773. analytics_doc.save();
  774. return 1
  775. return 0
  776. @get_execution_time
  777. def task_activity(group_id,url,doc):
  778. analytics_doc = initialize_analytics_obj(doc, group_id, 'task')
  779. if ins_objectid.is_valid(url[3]) is False:
  780. if(url[3]=="delete_task"):
  781. if ins_objectid.is_valid(url[4]) is True:
  782. analytics_doc.action = { "key" : "delete" , "phrase" : "deleted a" }
  783. analytics_doc.obj['task']['id'] = url[4]
  784. try :
  785. task_node = db['Nodes'].find_one({ "_id" : ObjectId(url[4])})
  786. analytics_doc.obj['task']['name'] = task_node[u'name']
  787. analytics_doc.obj['task']['url'] = task_node[u'url']
  788. except :
  789. pass
  790. analytics_doc.save();
  791. return 1
  792. elif url[3]=="edit":
  793. if ins_objectid.is_valid(url[4]) is True:
  794. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  795. analytics_doc.action = { "key" : "edit" , "phrase" : "edited a" }
  796. analytics_doc.obj['task']['id'] = url[4]
  797. try :
  798. task_node = db['Nodes'].find_one({ "_id" : ObjectId(url[4])})
  799. analytics_doc.obj['task']['name'] = task_node[u'name']
  800. analytics_doc.obj['task']['url'] = task_node[u'url']
  801. except :
  802. pass
  803. analytics_doc.save();
  804. return 1
  805. elif url[3]=="task" :
  806. if url[4] == "saveimage" :
  807. if u'has_data' in doc.keys() and doc[u'has_data']["POST"] == True :
  808. analytics_doc.action = { "key" : "save_image" , "phrase" : "saved an" }
  809. #analytics_doc.obj['task']['id'] = url[4]
  810. return 1
  811. else:
  812. n=node_collection.find_one({"_id":ObjectId(url[3])})
  813. try :
  814. author_id=n[u'created_by']
  815. auth=node_collection.find_one({"_type": "Author", "created_by": author_id})
  816. if auth[u'name']==doc[u'user']:
  817. created_at = n[u'created_at']
  818. if (doc[u'last_update'] - created_at).seconds < 5 :
  819. analytics_doc.action = { "key" : "create" , "phrase" : "created a" }
  820. analytics_doc.obj['task']['id'] = url[3]
  821. analytics_doc.obj['task']['name'] = n[u'name']
  822. analytics_doc.obj['task']['url'] = n[u'url']
  823. analytics_doc.save();
  824. return 1
  825. else :
  826. analytics_doc.action = { "key" : "view" , "phrase" : "viewed a" }
  827. analytics_doc.obj['task']['id'] = url[3]
  828. analytics_doc.obj['task']['name'] = n[u'name']
  829. analytics_doc.obj['task']['url'] = n[u'url']
  830. analytics_doc.save();
  831. return 1
  832. except :
  833. analytics_doc.action = { "key" : "view" , "phrase" : "viewed a" }
  834. analytics_doc.obj['task']['id'] = url[3]
  835. analytics_doc.save();
  836. return 1
  837. return 0
  838. @get_execution_time
  839. def dashbard_activity(group_id,url,doc):
  840. analytics_doc = initialize_analytics_obj(doc, group_id, 'dashboard')
  841. try :
  842. if(url[3] == 'group') :
  843. try :
  844. group_name, group_id = get_group_name_id(url[1])
  845. if group_name != None :
  846. analytics_doc.action = { "key" : "view" , "phrase" : "viewed dashboard of" }
  847. analytics_doc.obj['dashboard']['id'] = group_id
  848. analytics_doc.obj['dashboard']['name'] = group_name
  849. analytics_doc.save()
  850. return 1
  851. else :
  852. analytics_doc.action = { "key" : "view" , "phrase" : "viewed User group's Dashboard" }
  853. analytics_doc.obj['dashboard']['id'] = url[1]
  854. analytics_doc.obj['dashboard']['name'] = doc[u'user']
  855. analytics_doc.save()
  856. return 1
  857. except :
  858. pass
  859. except :
  860. try :
  861. user = node_collection.find_one({ "_type": "Author", "created_by" : int(url[1])})
  862. try :
  863. analytics_doc.action = { "key" : "view" , "phrase" : "viewed profile of" }
  864. analytics_doc.obj['dashboard']['id'] = url[1]
  865. analytics_doc.obj['dashboard']['name'] = user[u'name']
  866. analytics_doc.save();
  867. return 1
  868. except :
  869. pass
  870. except :
  871. pass
  872. return 0
  873. @get_execution_time
  874. def default_activity(group_id,url,doc):
  875. return 1
  876. def event_activity(group_id,url,doc):
  877. return 0
  878. def group_activity(group_id,url,doc):
  879. return 0
  880. def image_activity(group_id,url,doc):
  881. return 0
  882. def video_activity(group_id,url,doc):
  883. return 0
  884. def Gid(group):
  885. group_id = group;
  886. ins_objectid = ObjectId()
  887. if ins_objectid.is_valid(group_id) is False:
  888. group_ins = node_collection.find_one({'_type': "Group", "name": group_id})
  889. #auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  890. if group_ins:
  891. group_id = str(group_ins._id)
  892. else:
  893. auth = node_collection.one({'_type': 'Author', 'name': group_id })
  894. if auth:
  895. group_id = str(auth._id)
  896. pass
  897. else:
  898. pass
  899. return group_id