def remote_message_send(request, message, bookid): """ Called when user is sending message to chat channel L{bookid}. @type request: C{django.http.HttpRequest} @param request: Client Request object @type message: C{dict} @param message: Message object @type bookid: C{string} @param bookid: Unique Book id """ import sputnik sputnik.addMessageToChannel( request, "/chat/%s/" % bookid, { "command": "message_received", "email": request.user.email, "from": request.user.username, "important": message["important"], "message": message["message"], }, ) return {}
def remote_ping(request, message): import sputnik sputnik.addMessageToChannel(request, "/booki/", {}) _now = time.time() try: locks = sputnik.rkeys("booki:*:locks:*") except: return for key in locks: lastAccess = sputnik.get(key) if type(lastAccess) in [type(' '), type(u' ')]: try: lastAccess = decimal.Decimal(lastAccess) except: continue if lastAccess and decimal.Decimal("%f" % _now) - lastAccess > 30: sputnik.rdelete(key) m = re.match("booki:(\d+):locks:(\d+):(\w+)", key) if m: sputnik.addMessageToChannel(request, "/booki/book/%s/" % m.group(1), {"command": "chapter_status", "chapterID": m.group(2), "status": "normal", "username": m.group(3)}, myself = True)
def remote_change_status(request, message, bookid, version): # chapterID # statusID chapter = models.Chapter.objects.get(id=int(message["chapterID"])) status = models.BookStatus.objects.get(id=int(message["statusID"])) chapter.status = status try: chapter.save() sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "change_status", "chapterID": message["chapterID"], "statusID": int(message["statusID"]), "username": request.user.username}) sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has changed status of chapter "%s" to "%s".' % (request.user.username, chapter.title, status.name)}, myself=True) except: transaction.rollback() else: transaction.commit() return {}
def push_notification(request, message, timeline): import sputnik sputnik.addMessageToChannel(request, "/messaging/%s/" % timeline, { "command": "message_received", "message": message })
def remote_mood_set(request, message, profileid): # should check permissions from django.utils.html import strip_tags ## maximum size is 30 characters only ## html tags are removed moodMessage = strip_tags(message.get("value",""))[:30] import booki.account.signals booki.account.signals.account_status_changed.send(sender = request.user, message = message.get('value', '')) # save new permissions profile = request.user.get_profile() profile.mood = moodMessage try: profile.save() except: transaction.rollback() else: transaction.commit() ## propagate to other users ## probably should only send it to /booki/ channel import sputnik for chnl in sputnik.smembers("sputnik:channels"): if sputnik.sismember("sputnik:channel:%s:users" % message['channel'], request.user.username): sputnik.addMessageToChannel(request, chnl, {"command": "user_status_changed", "from": request.user.username, "message": moodMessage}, myself=True) return {}
def remote_chapters_changed(request, message, bookid, version): lst = [chap[5:] for chap in message["chapters"]] lstHold = [chap[5:] for chap in message["hold"]] book = models.Book.objects.get(id=bookid) book_version = getVersion(book, version) weight = len(lst) logBookHistory(book = book, version = book_version, user = request.user, kind = "chapter_reorder") for chap in lst: if chap[0] == 's': m = models.BookToc.objects.get(id__exact=int(chap[1:])) m.weight = weight m.save() else: try: m = models.BookToc.objects.get(chapter__id__exact=int(chap)) m.weight = weight m.save() except: chptr = models.Chapter.objects.get(id__exact=int(chap)) m = models.BookToc(book = book, version = book_version, name = "SOMETHING", chapter = chptr, weight = weight, typeof=1) m.save() weight -= 1 if message["kind"] == "remove": if type(message["chapter_id"]) == type(u' ') and message["chapter_id"][0] == 's': m = models.BookToc.objects.get(id__exact=message["chapter_id"][1:]) m.delete() else: m = models.BookToc.objects.get(chapter__id__exact=int(message["chapter_id"])) m.delete() # addMessageToChannel(request, "/chat/%s/%s/" % (projectid, bookid), {"command": "message_info", "from": request.user.username, "message": 'User %s has rearranged chapters.' % request.user.username}) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapters_changed", "ids": lst, "hold_ids": lstHold, "kind": message["kind"], "chapter_id": message["chapter_id"]}) # TODO # this should be changed, to check for errors transaction.commit() return {}
def remote_mood_set(request, message, profileid): """ Sets new mood for this profile. Input: - value @type request: C{django.http.HttpRequest} @param request: Client Request object @type message: C{dict} @param message: Message object @type profileid: C{string} @param profile: Unique Profile id """ # should check permissions from django.utils.html import strip_tags ## maximum size is 30 characters only ## html tags are removed moodMessage = strip_tags(message.get("value", ""))[:30] import booki.account.signals booki.account.signals.account_status_changed.send(sender=request.user, message=message.get( 'value', '')) # save new permissions profile = request.user.get_profile() profile.mood = moodMessage try: profile.save() except: transaction.rollback() else: transaction.commit() ## propagate to other users ## probably should only send it to /booki/ channel import sputnik for chnl in sputnik.smembers("sputnik:channels"): if sputnik.sismember( "sputnik:channel:%s:users" % message['channel'], request.user.username): sputnik.addMessageToChannel( request, chnl, { "command": "user_status_changed", "from": request.user.username, "message": moodMessage }, myself=True) return {}
def remote_message_send(request, message, bookid): import sputnik sputnik.addMessageToChannel( request, "/chat/%s/" % bookid, {"command": "message_received", "from": request.user.username, "message": message["message"]}, ) return {}
def remote_chapter_save(request, message, bookid, version): # TODO # put this outside in common module # or maybe even betterm put it in the Model book = models.Book.objects.get(id=bookid) book_version = getVersion(book, version) chapter = models.Chapter.objects.get(id=int(message["chapterID"])) if message.get("minor", False) != True: history = logChapterHistory(chapter = chapter, content = message["content"], user = request.user, comment = message.get("comment", ""), revision = chapter.revision+1) logBookHistory(book = chapter.book, version = book_version, chapter = chapter, chapter_history = history, user = request.user, args = {"comment": message.get("comment", ""), "author": message.get("author", ""), "authorcomment": message.get("authorcomment", "")}, kind = 'chapter_save') chapter.revision += 1 chapter.content = message["content"]; try: chapter.save() sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has saved chapter "%s".' % (request.user.username, chapter.title)}, myself=True) except: transaction.rollback() else: transaction.commit() if not message['continue']: sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_status", "chapterID": message["chapterID"], "status": "normal", "username": request.user.username}) sputnik.rdelete("booki:%s:locks:%s:%s" % (bookid, message["chapterID"], request.user.username)) # fire the signal import booki.editor.signals booki.editor.signals.chapter_modified.send(sender = book_version, chapter = chapter, user = request.user) return {}
def remote_chapter_status(request, message, bookid, version): if message["status"] == "normal": sputnik.rdelete("booki:%s:locks:%s:%s" % (bookid, message["chapterID"], request.user.username)) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_status", "chapterID": message["chapterID"], "status": message["status"], "username": request.user.username}) return {}
def remote_create_section(request, message, bookid, version): import datetime book = models.Book.objects.get(id=bookid) book_version = getVersion(book, version) ch = models.BookToc.objects.filter(book=book, version=book_version, name=message['chapter'], typeof=0) if len(list(ch)) > 0: return {"created": False} c = models.BookToc(book = book, version = book_version, name = message["chapter"], chapter = None, weight = 0, typeof=0) result = True try: c.save() except: result = False transaction.rollback() else: logBookHistory(book = book, version = book_version, user = request.user, args = {"title": message["chapter"]}, kind = 'section_create') transaction.commit() result = ("s%s" % c.id, c.name, None, c.typeof) sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has created new section "%s".' % (request.user.username, message["chapter"])}, myself=True) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_create", "chapter": result, "typeof": c.typeof}, myself = True) return {"created": result}
def remote_ping(request, message): """ Sends ping to the server. Just so we know client is still alive. It also removes old locks. This is not the place to do it at all, but once we have normal scheduled calls, will put it there. :Args: - request (:class:`django.http.HttpRequest`): Client Request object - message (dict): Message object """ import sputnik sputnik.addMessageToChannel(request, "/booktype/", {}) # kill old chapters which are no longer under edit keys = sputnik.rkeys("booktype:*:*:editlocks:*") for key in keys: last_ping = sputnik.get(key) try: last_ping = decimal.Decimal(last_ping) except Exception as e: logger.exception(e) if last_ping and decimal.Decimal( "%f" % time.time()) - last_ping > Chapter.EDIT_PING_SECONDS_MAX_DELTA: sputnik.rdelete(key) m = re.match("booktype:(\d+):(\d+).(\d+):editlocks:(\d+):(\w+)", key) if m: bookid, version, chapter_id, username = (m.group(1), "{0}.{1}".format( m.group(2), m.group(3)), m.group(4), m.group(5)) sputnik.addMessageToChannel(request, "/booktype/book/%s/%s/" % (bookid, version), { "command": "chapter_state", "chapterID": chapter_id, "state": "normal", "username": username }, myself=True)
def remote_message_send(request, message, bookid): """ Called when user is sending message to chat channel L{bookid}. @type request: C{django.http.HttpRequest} @param request: Client Request object @type message: C{dict} @param message: Message object @type bookid: C{string} @param bookid: Unique Book id """ import sputnik sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_received", "from": request.user.username, "message": message["message"]}) return {}
def remote_ping(request, message): """ Sends ping to the server. Just so we know client is still alive. It also removes old locks. This is not the place to do it at all, but once we have normal scheduled calls, will put it there. @type request: C{django.http.HttpRequest} @param request: Client Request object @type message: C{dict} @param message: Message object """ import sputnik sputnik.addMessageToChannel(request, "/booki/", {}) _now = time.time() try: locks = sputnik.rkeys("booki:*:locks:*") except: return for key in locks: lastAccess = sputnik.get(key) if type(lastAccess) in [type(' '), type(u' ')]: try: lastAccess = decimal.Decimal(lastAccess) except: continue if lastAccess and decimal.Decimal("%f" % _now) - lastAccess > 30: sputnik.rdelete(key) m = re.match("booki:(\d+):locks:(\d+):(\w+)", key) if m: sputnik.addMessageToChannel(request, "/booki/book/%s/" % m.group(1), { "command": "chapter_status", "chapterID": m.group(2), "status": "normal", "username": m.group(3) }, myself=True)
def remote_message_send(request, message, bookid): """ Called when user is sending message to chat channel L{bookid}. @type request: C{django.http.HttpRequest} @param request: Client Request object @type message: C{dict} @param message: Message object @type bookid: C{string} @param bookid: Unique Book id """ try: book = Book.objects.get(id=int(bookid)) except Book.DoesNotExist: raise ObjectDoesNotExist except Book.MultipleObjectsReturned: raise ObjectDoesNotExist book_security = security.get_security_for_book(request.user, book) has_permission = book_security.can_edit() if not has_permission: raise PermissionDenied # get chat thread chat_thread, _ = ChatThread.objects.get_or_create(book=book) # create message chat_message = ChatMessage() chat_message.thread = chat_thread chat_message.sender = request.user chat_message.text = message["message"] chat_message.save() sputnik.addMessageToChannel( request, "/chat/%s/" % bookid, { "command": "message_received", "email": request.user.email, "from": request.user.username, "important": message["important"], "message": message["message"] }) return {}
def remote_ping(request, message): """ Sends ping to the server. Just so we know client is still alive. It also removes old locks. This is not the place to do it at all, but once we have normal scheduled calls, will put it there. @type request: C{django.http.HttpRequest} @param request: Client Request object @type message: C{dict} @param message: Message object """ import sputnik sputnik.addMessageToChannel(request, "/booki/", {}) _now = time.time() try: locks = sputnik.rkeys("booki:*:locks:*") except: return for key in locks: lastAccess = sputnik.get(key) if type(lastAccess) in [type(' '), type(u' ')]: try: lastAccess = decimal.Decimal(lastAccess) except: continue if lastAccess and decimal.Decimal("%f" % _now) - lastAccess > 30: sputnik.rdelete(key) m = re.match("booki:(\d+):locks:(\d+):(\w+)", key) if m: sputnik.addMessageToChannel(request, "/booki/book/%s/" % m.group(1), {"command": "chapter_status", "chapterID": m.group(2), "status": "normal", "username": m.group(3)}, myself = True)
def remote_revert_revision(request, message, bookid, version): from booki.editor.views import getVersion book = models.Book.objects.get(id=bookid) book_ver = getVersion(book, version) chapter = models.Chapter.objects.get(version=book_ver, url_title=message["chapter"]) revision = models.ChapterHistory.objects.get(revision=message["revision"], chapter__url_title=message["chapter"], chapter__version=book_ver.id) # TODO # does chapter history really needs to keep content or it can only keep reference to chapter history = logChapterHistory(chapter = chapter, content = revision.content, user = request.user, comment = "Reverted to revision %s." % message["revision"], revision = chapter.revision+1) logBookHistory(book = book, version = book_ver, chapter = chapter, chapter_history = history, user = request.user, args = {}, kind = 'chapter_save') chapter.revision += 1 chapter.content = revision.content; try: chapter.save() except: transaction.rollback() else: transaction.commit() sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has reverted chapter "%s" to revision %s.' % (request.user.username, chapter.title, message["revision"])}, myself=True) return {}
def remote_message_send(request, message, bookid): """ Called when user is sending message to chat channel L{bookid}. @type request: C{django.http.HttpRequest} @param request: Client Request object @type message: C{dict} @param message: Message object @type bookid: C{string} @param bookid: Unique Book id """ try: book = Book.objects.get(id=int(bookid)) except Book.DoesNotExist: raise ObjectDoesNotExist except Book.MultipleObjectsReturned: raise ObjectDoesNotExist book_security = security.get_security_for_book(request.user, book) has_permission = book_security.can_edit() if not has_permission: raise PermissionDenied # get chat thread chat_thread, _ = ChatThread.objects.get_or_create(book=book) # create message chat_message = ChatMessage() chat_message.thread = chat_thread chat_message.sender = request.user chat_message.text = message["message"] chat_message.save() sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_received", "email": request.user.email, "from": request.user.username, "important": message["important"], "message": message["message"]}) return {}
def send_notification(request, bookid, version, message, *message_args): """Send notification. Add notification message to channel Args: reuest: Client Request object bookid: Unique Book id version: Book version message: Notification message key message_args: positional arguments for message format """ channel_name = '/booktype/book/%s/%s/' % (bookid, version) user = request.user sputnik.addMessageToChannel(request, channel_name, { 'command': 'notification', 'message': message, 'username': user.username, 'message_args': message_args }, myself=False)
def remote_get_chapter(request, message, bookid, version): res = {} chapter = models.Chapter.objects.get(id=int(message["chapterID"])) res["title"] = chapter.title res["content"] = chapter.content if not message.get("lock", True): return res import time # set the initial timer for editor sputnik.set("booki:%s:locks:%s:%s" % (bookid, message["chapterID"], request.user.username), time.time()) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_status", "chapterID": message["chapterID"], "status": "edit", "username": request.user.username}) return res
def remote_ping(request, message): """ Sends ping to the server. Just so we know client is still alive. It also removes old locks. This is not the place to do it at all, but once we have normal scheduled calls, will put it there. :Args: - request (:class:`django.http.HttpRequest`): Client Request object - message (dict): Message object """ import sputnik sputnik.addMessageToChannel(request, "/booktype/", {}) # kill old chapters which are no longer under edit keys = sputnik.rkeys("booktype:*:*:editlocks:*") for key in keys: last_ping = sputnik.get(key) try: last_ping = decimal.Decimal(last_ping) except Exception as e: logger.exception(e) if last_ping and decimal.Decimal("%f" % time.time()) - last_ping > Chapter.EDIT_PING_SECONDS_MAX_DELTA: sputnik.rdelete(key) m = re.match("booktype:(\d+):(\d+).(\d+):editlocks:(\d+):(\w+)", key) if m: bookid, version, chapter_id, username = (m.group(1), "{0}.{1}".format(m.group(2), m.group(3)), m.group(4), m.group(5)) sputnik.addMessageToChannel(request, "/booktype/book/%s/%s/" % (bookid, version), {"command": "chapter_state", "chapterID": chapter_id, "state": "normal", "username": username}, myself=True)
def remote_notes_save(request, message, bookid, version): book = models.Book.objects.get(id=bookid) book_notes = models.BookNotes.objects.filter(book=book) notes = message.get("notes") book_notes_obj = None if len(book_notes) == 0: book_notes_obj = models.BookNotes( book = book , notes = notes) else: book_notes_obj = book_notes[0] book_notes_obj.notes = notes try: book_notes_obj.save() except: transaction.rollback() else: sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has saved notes for book "%s".' % (request.user.username, book.title)}, myself=True) transaction.commit() return {}
def remote_chapter_rename(request, message, bookid, version): book = models.Book.objects.get(id=bookid) book_version = getVersion(book, version) chapter = models.Chapter.objects.get(id=int(message["chapterID"])) oldTitle = chapter.title chapter.title = message["chapter"]; try: chapter.save() except: transaction.rollback() else: logBookHistory(book = chapter.book, version = book_version, chapter = chapter, user = request.user, args = {"old": oldTitle, "new": message["chapter"]}, kind = "chapter_rename") sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has renamed chapter "%s" to "%s".' % (request.user.username, oldTitle, message["chapter"])}, myself=True) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_status", "chapterID": message["chapterID"], "status": "normal", "username": request.user.username}) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_rename", "chapterID": message["chapterID"], "chapter": message["chapter"]}) transaction.commit() return {}
def remote_create_chapter(request, message, bookid, version): import datetime # BookVersion treba uzeti book = models.Book.objects.get(id=bookid) book_version = getVersion(book, version) from django.template.defaultfilters import slugify url_title = slugify(message["chapter"]) # here i should probably set it to default project status s = models.BookStatus.objects.filter(book=book).order_by("weight")[0] ch = models.Chapter.objects.filter(book=book, version=book_version, url_title=url_title) if len(list(ch)) > 0: return {"created": False} content = u'<h1>%s</h1>' % message["chapter"] chapter = models.Chapter(book = book, version = book_version, url_title = url_title, title = message["chapter"], status = s, content = content, created = datetime.datetime.now(), modified = datetime.datetime.now()) try: chapter.save() except: transaction.rollback() return {"created": False} else: # this should be solved in better way # should have createChapter in booki.utils.book module toc_items = len(book_version.getTOC())+1 for itm in models.BookToc.objects.filter(version = book_version, book = book): itm.weight = toc_items itm.save() toc_items -= 1 tc = models.BookToc(version = book_version, book = book, name = message["chapter"], chapter = chapter, weight = 1, typeof = 1) try: tc.save() except: transaction.rollback() return {"created": False} history = logChapterHistory(chapter = chapter, content = content, user = request.user, comment = message.get("comment", ""), revision = chapter.revision) logBookHistory(book = book, version = book_version, chapter = chapter, chapter_history = history, user = request.user, kind = 'chapter_create') transaction.commit() result = (chapter.id, chapter.title, chapter.url_title, 1, s.id) sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has created new chapter "%s".' % (request.user.username, message["chapter"])}, myself=True) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_create", "chapter": result}, myself = True) return {"created": True}
def push_notification(request, message, timeline): import sputnik sputnik.addMessageToChannel(request, "/messaging/%s/" % timeline, {"command": "message_received", "message": message})
def remote_chapter_split(request, message, bookid, version): book = models.Book.objects.get(id=bookid) book_version = getVersion(book, version) logBookHistory(book = book, version = book_version, user = request.user, kind = 'chapter_split') allChapters = [] try: originalChapter = models.Chapter.objects.get(id=int(message["chapterID"])) except: originalChapter = None try: tocChapter = models.BookToc.objects.get(book=book, chapter__id__exact=message["chapterID"]) except: tocChapter = None import datetime from django.template.defaultfilters import slugify if tocChapter: allChapters = [chap for chap in models.BookToc.objects.filter(book=book).order_by("-weight")] initialPosition = len(allChapters)-tocChapter.weight else: initialPosition = 0 s = models.BookStatus.objects.filter(book=book).order_by("weight")[0] n = 0 for chap in message["chapters"]: chapter = models.Chapter(book = book, url_title = slugify(chap[0]), title = chap[0], status = s, content = '<h1>%s</h1>%s' % (chap[0], chap[1]), created = datetime.datetime.now(), modified = datetime.datetime.now()) chapter.save() if tocChapter: m = models.BookToc(book = book, chapter = chapter, name = chap[0], weight = 0, typeof = 1) m.save() allChapters.insert(1+initialPosition+n, m) n += 1 if originalChapter: sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": 'User %s has split chapter "%s".' % (request.user.username, originalChapter.title)}, myself=True) originalChapter.delete() if tocChapter: tocChapter.delete() n = len(allChapters) for chap in allChapters: try: chap.weight = n chap.save() n -= 1 except: pass ## get chapters chapters = getTOCForBook(book_version) holdChapters = getHoldChapters(book_version) sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "chapter_split", "chapterID": message["chapterID"], "chapters": chapters, "hold": holdChapters, "username": request.user.username}, myself = True) transaction.commit() return {}
def remote_publish_book(request, message, bookid, version): book = models.Book.objects.get(id=bookid) sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "message_info", "from": request.user.username, "message": '"%s" is being published.' % (book.title, )}, myself=True) import urllib2 import urllib publishMode = message.get("publish_mode", "epub") destination = "nowhere" if message.get("is_archive", False): destination = "archive.org" args = {'book': book.url_title, 'project': 'export', 'mode': publishMode, 'server': THIS_BOOKI_SERVER, 'destination': destination, 'max-age': 0, } def _isSet(name): if message.get(name, None): if name == 'grey_scale': args['grey_scale'] = 'yes' else: args[name] = message.get(name) _isSet('title') _isSet('license') _isSet('isbn') _isSet('toc_header') _isSet('booksize') _isSet('page_width') _isSet('page_height') _isSet('top_margin') _isSet('side_margin') _isSet('gutter') _isSet('columns') _isSet('column_margin') _isSet('grey_scale') _isSet('css') data = urllib.urlencode(args) req = urllib2.Request(OBJAVI_URL, data) f = urllib2.urlopen(req) # f = urllib2.urlopen("%s?book=%s&project=export&mode=%s&server=booki.flossmanuals.net&destination=%s" % (urlPublish, book.url_title, publishMode, destination)) ta = f.read() lst = ta.split("\n") dta, dtas3 = "", "" if len(lst) > 0: dta = lst[0] if len(lst) > 1: dtas3 = lst[1] return {"dtaall": ta, "dta": dta, "dtas3": dtas3}
def remote_init_editor(request, message, bookid, version): book = models.Book.objects.get(id=bookid) book_version = getVersion(book, version) ## get chapters chapters = getTOCForBook(book_version) holdChapters = getHoldChapters(book_version) ## get users def _getUserName(a): if a == request.sputnikID: return "<b>%s</b>" % a return a try: users = [_getUserName(m) for m in list(sputnik.smembers("sputnik:channel:%s:channel" % message["channel"]))] except: users = [] ## get workflow statuses statuses = [(status.id, status.name) for status in models.BookStatus.objects.filter(book=book).order_by("-weight")] ## get attachments try: attachments = getAttachments(book_version) except: attachments = [] ## get metadata metadata = [{'name': v.name, 'value': v.getValue()} for v in models.Info.objects.filter(book=book)] ## notify others sputnik.addMessageToChannel(request, "/chat/%s/" % bookid, {"command": "user_joined", "user_joined": request.user.username}, myself = False) ## get licenses licenses = [(elem.abbrevation, elem.name) for elem in models.License.objects.all().order_by("name")] ## get online users try: _onlineUsers = sputnik.smembers("sputnik:channel:%s:users" % message["channel"]) except: _onlineUsers = [] if request.user.username not in _onlineUsers: try: sputnik.sadd("sputnik:channel:%s:users" % message["channel"], request.user.username) _onlineUsers.append(request.user.username) except: pass ## get mood message for current user ## send mood as seperate message ## set notifications to other clients profile = request.user.get_profile() if profile: moodMessage = profile.mood; else: moodMessage = '' sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version), {"command": "user_add", "username": request.user.username, "mood": moodMessage} ) ## get online users and their mood messages from django.contrib.auth.models import User def _getUser(_user): try: _u = User.objects.get(username=_user) return (_user, _u.get_profile().mood) except: return None onlineUsers = [x for x in [_getUser(x) for x in _onlineUsers] if x] # for now, this is one big temp here import time, decimal, re _now = time.time() locks = {} try: for key in sputnik.rkeys("booki:*:locks:*"): lastAccess = sputnik.get(key) if type(lastAccess) in [type(' '), type(u' ')]: try: lastAccess = decimal.Decimal(lastAccess) except: continue if lastAccess and decimal.Decimal("%f" % _now) - lastAccess <= 30: m = re.match("booki:(\d+):locks:(\d+):(\w+)", key) if m: if m.group(1) == bookid: locks[m.group(2)] = m.group(3) except: pass return {"licenses": licenses, "chapters": chapters, "metadata": metadata, "hold": holdChapters, "users": users, "locks": locks, "statuses": statuses, "attachments": attachments, "onlineUsers": list(onlineUsers)}