Source

py4u-opensource / news / model.py

  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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# -*- coding: utf-8 *-*
import string,random
from flask import g,session
import sqlite3
import hashlib
import datetime
from configure import configure
class User:
    def __init__(self,email,nickname,password):
        self.id = None
        self.email = email
        self.nickname = nickname
        self.avatar = None
        self.password = not password or hashlib.sha224(password).hexdigest()
        self.create_date = None
        self.reputation = None

    def get_nickname(self):
        c = g.db.cursor()
        c.execute("SELECT nickname FROM user WHERE email=:email",\
                                {'email':self.email})
        return c.fetchone()['nickname']

    @staticmethod
    def get_avatar_by_id(id):
        c = g.db.cursor()
        c.execute("SELECT avatar FROM user WHERE id=:id",\
                                {'id':id})
        return c.fetchone()['avatar']

    @staticmethod
    def get_user_by_id(id):
        c = g.db.cursor()
        c.execute("SELECT * FROM user WHERE id=:id",\
                                {'id':id})
        result = c.fetchone()
        tempuser = User(result['email'],result['nickname'],None)
        tempuser.avatar = result['avatar']
        tempuser.create_date = result['create_date']
        tempuser.reputation = result['reputation']
        return tempuser

    @staticmethod
    def change_avatar_by_id(id,avatar):
        c = g.db.cursor()
        c.execute("UPDATE user SET avatar = :avatar WHERE id=:id",\
                                {'id':id,'avatar':avatar})
        g.db.commit()

    def is_valid(self):
        c = g.db.cursor()
        c.execute("SELECT * FROM user WHERE email=:email AND password=:password",\
                                {'email':self.email,'password':self.password})
        tempuser = c.fetchone()
        if(not tempuser):
            return False
        self.id = tempuser['id']
        self.email = tempuser['email']
        self.nickname = tempuser['nickname']
        self.avatar = tempuser['avatar']
        self.create_date = tempuser['create_date']
        self.reputation = tempuser['reputation']
        return True

    def toggle_star_book(self, bookid):
        c = g.db.cursor()
        c.execute("SELECT userid FROM star_book WHERE userid=:userid AND bookid=:bookid",\
                                {'userid':self.id, 'bookid':bookid})
        if(c.fetchone()):
            c.execute("DELETE FROM star_book WHERE userid=:userid AND bookid=:bookid",\
                                {'userid':self.id, 'bookid':bookid})
        else:
            c.execute("INSERT INTO star_book(userid, bookid) VALUES (:userid, :bookid)",\
                                {'userid':self.id, 'bookid':bookid})
        g.db.commit()
    
    def get_stared_bookid(self):
        c = g.db.cursor()
        c.execute("SELECT bookid FROM star_book WHERE userid=:userid",\
                                {'userid':self.id})
        bookidset = set([x['bookid'] for x in c.fetchall()])
        return bookidset
                                
                                
                                
    def is_email_exsit(self):
        c = g.db.cursor()
        c.execute("SELECT nickname FROM user WHERE email=:email",\
                                {'email':self.email})
        if(not c.fetchone()):
            return False
        return True

    def is_nickname_exsit(self):
        c = g.db.cursor()
        c.execute("SELECT nickname FROM user WHERE nickname=:nickname",\
                                {'nickname':self.nickname})
        if(not c.fetchone()):
            return False
        return True

    def is_exist(self):
        c = g.db.cursor()
        c.execute("SELECT nickname FROM user WHERE email=:email or nickname=:nickname",\
                                {'email':self.email,'nickname':self.nickname})
        if(not c.fetchone()):
            return False
        return True


    def update(self):
        c = g.db.cursor()
        self.create_date = datetime.datetime.now()
        c.execute("UPDATE user SET nickname =:nickname, email =:email,\
                   avatar =:avatar, reputation=:reputation WHERE id=:id",\
                                {"nickname":self.nickname,"email":self.email,"avatar":self.avatar,"reputation":self.reputation,"id":self.id})
        g.db.commit()
    def save(self):
        c = g.db.cursor()
        self.create_date = datetime.datetime.now()
        self.reputation = 0
        c.execute("INSERT INTO user(nickname,email,password,create_date,reputation) VALUES (?,?,?,?,?)",\
                                (self.nickname,self.email,self.password,self.create_date,self.reputation))
        self.id = c.lastrowid
        g.db.commit()

    def vote_for(self,postid):
        c = g.db.cursor()
        if(self.reputation is None):
            c.execute("SELECT reputation FROM user WHERE id=:id",{'id':self.id})
            self.reputation = c.fetchone()['reputation']
        import math
        score = 1
        if(self.reputation > 2):
            score = int(math.log(self.reputation , 2))
        c.execute("INSERT OR REPLACE INTO vote(userid, postid, popularity) VALUES (?,?,?)",(self.id,postid,score))
        g.db.commit()



    @staticmethod
    def password_generate(size=8, chars=string.ascii_letters + string.digits):
        return ''.join(random.choice(chars) for x in range(size))

    @staticmethod
    def reset_password_for(email):
        c = g.db.cursor()
        c.execute("SELECT nickname FROM user WHERE email=:email",\
                                {'email':email})
        if(not c.fetchone()):
            return None
        password = User.password_generate()
        md5pw = hashlib.sha224(password).hexdigest()
        c.execute("UPDATE user SET password =:password WHERE email=:email",\
                                {'email':email,'password':md5pw})
        g.db.commit()
        return password
        
    def create_post_activity(self, points, postid):
        info = "<span>You post a post and gain 2 point</span>"
        tempac = Activity(info,self.id)
        tempac.save()

class Post:
    def __init__(self, title, link, des, post_date = None):
        self.id = None
        self.title = title
        self.link = link
        self.des = des
        self.post_date = post_date
        self.posterid = None
        self.poster = None

    @staticmethod
    def get_post_byid(id):
        c = g.db.cursor()
        c.execute("SELECT * FROM post WHERE id=:id",\
                                {"id":id})
        post = c.fetchone()
        if(post is None):
            return None
        temppost = Post(post['title'], post['link'],post['des'],post['post_date'])
        temppost.id = post['id']
        temppost.posterid = post['posterid']
        return temppost
        
    @staticmethod
    def is_exist(id):
        c = g.db.cursor()
        c.execute("SELECT id FROM post WHERE id=:id",\
                                {"id":id})
        return  c.fetchone() is not None

    def init_post_poster(self):
        c = g.db.cursor()
        c.execute("SELECT nickname, id,reputation FROM user where id=:id",\
                                {"id":self.posterid})
        tempresult = c.fetchone()
        user = User(None,tempresult['nickname'],None)
        user.reputation = tempresult['reputation']
        user.id = tempresult['id']
        self.poster = user

    @staticmethod
    def get_posts_by_postdate(limit = configure.POSTNUMBER_PER_PAGE, offset =0):
        c = g.db.cursor()
        c.execute("SELECT * FROM post WHERE posterid is not NULL ORDER BY post_date DESC LIMIT :limit OFFSET :offset ",\
                                {"limit":limit,"offset":offset*limit})
        result = c.fetchall()
        posts = []
        for post in result:
            temppost = Post(post['title'], post['link'],post['des'],post['post_date'])
            temppost.id = post['id']
            temppost.posterid = post['posterid']
            c.execute("SELECT nickname, id,reputation FROM user where id=:id",\
                                {"id":temppost.posterid})
            tempresult = c.fetchone()
            user = User(None,tempresult['nickname'],None)
            user.reputation = tempresult['reputation']
            user.id = tempresult['id']
            temppost.poster = user
            posts.append(temppost)
        return posts

    @staticmethod
    def get_hot_posts(limit = configure.POSTNUMBER_PER_PAGE, offset =0):
        c = g.db.cursor()
        c.execute("SELECT * FROM post WHERE julianday('now') - julianday(post_date) <= :save_post_days AND posterid is not NULL\
                   LIMIT :limit OFFSET :offset",\
                                {"limit":limit,"offset":offset*limit,'save_post_days':configure.POST_SAVE})
        result = c.fetchall()
        posts = []
        for post in result:
            temppost = Post(post['title'], post['link'],post['des'],post['post_date'])
            temppost.id = post['id']
            temppost.posterid = post['posterid']
            c.execute("SELECT nickname, id,reputation FROM user where id=:id",\
                                {"id":temppost.posterid})
            tempresult = c.fetchone()
            user = User(None,tempresult['nickname'],None)
            user.reputation = tempresult['reputation']
            user.id = tempresult['id']
            temppost.poster = user
            posts.append(temppost)
        return posts

    @staticmethod
    def get_deadpool_posts(limit = configure.POSTNUMBER_PER_PAGE, offset =0):
        c = g.db.cursor()
        c.execute("SELECT * FROM post WHERE julianday('now') - julianday(post_date) > :save_post_days AND posterid is not NULL\
                    ORDER BY post_date DESC LIMIT :limit OFFSET :offset",\
                                {"limit":limit,"offset":offset*limit,'save_post_days':configure.POST_SAVE})
        result = c.fetchall()
        posts = []
        for post in result:
            temppost = Post(post['title'], post['link'],post['des'],post['post_date'])
            temppost.id = post['id']
            temppost.posterid = post['posterid']
            c.execute("SELECT nickname, id,reputation FROM user where id=:id",\
                                {"id":temppost.posterid})
            tempresult = c.fetchone()
            user = User(None,tempresult['nickname'],None)
            user.reputation = tempresult['reputation']
            user.id = tempresult['id']
            temppost.poster = user
            posts.append(temppost)
        return posts

    @staticmethod
    def delete_byid(id):
        c = g.db.cursor()
        c.execute("DELETE FROM post WHERE id=:id",\
                                {'id':id})
        g.db.commit()

    def save(self):
        c = g.db.cursor()
        self.link = self.link.strip()
        if(not self.link.startswith('http')):
            self.link = 'http://' + self.link
        c.execute("INSERT INTO post(title,link,des,post_date,posterid) VALUES (?,?,?,?,?)",\
                                (self.title,self.link,self.des,datetime.datetime.now(),session['user'].id))
        self.id = c.lastrowid
        g.db.commit()
        
    def special_save(self):
        c = g.db.cursor()
        self.link = self.link.strip()
        c.execute("INSERT INTO post(title,link,post_date) VALUES (?,?,?)",\
                                (self.title,self.link,datetime.datetime.now()))
        self.id = c.lastrowid
        g.db.commit()

    @property
    def domain(self):
        import urlparse
        rv = urlparse.urlparse(self.link).netloc
        if rv.startswith("www."):
            rv = rv[4:]
        return rv

    @property
    def score(self):
        c = g.db.cursor()
        c.execute("SELECT popularity FROM vote WHERE postid=:id",{'id':self.id})
        scores = [x['popularity'] for x in c.fetchall()]
        return sum(scores)
    @property
    def comments_number(self):
        c = g.db.cursor()
        c.execute("SELECT COUNT(*) AS number FROM comment WHERE postid=:id",{'id':self.id})
        result = c.fetchone()
        number = result['number'] if result else 0
        return number

class Vote:
    def __init__(self, userid, posterid, popularity = 0):
        self.userid = userid
        self.postid = postid
        self.popularity = popularity


class Comment:
    def __init__(self, postid, content, userid, parentid = None):
        self.id = None
        self.postid = postid
        self.content = content
        self.userid = userid
        self.poster =None
        self.parentid = parentid
        self.create_date =None
        self.children = []
    def save(self):
        c = g.db.cursor()
        self.create_date = datetime.datetime.now()
        c.execute("INSERT INTO comment(postid,content,userid,parentid,create_date) VALUES (?,?,?,?,?)",\
                                (self.postid,self.content,self.userid,self.parentid,self.create_date))
        self.id = c.lastrowid
        g.db.commit()

    @staticmethod
    def get_comments_by_postid(postid):
        c = g.db.cursor()
        c.execute("SELECT * FROM comment WHERE postid=:id AND parentid is NULL ORDER BY create_date",{'id':postid})
        result = c.fetchall()
        comments = []
        for tempvalue in result:
            tempcomment = Comment(tempvalue['postid'],tempvalue['content'],tempvalue['userid'],tempvalue['parentid'])
            tempcomment.id = tempvalue['id']
            tempcomment.create_date = tempvalue['create_date']
            tempcomment.init_comment_poster()
            tempcomment.init_children()
            comments.append(tempcomment)
        return comments

    def init_comment_poster(self):
        self.poster = User.get_user_by_id(self.userid)

    def init_children(self):
        c = g.db.cursor()
        c.execute("SELECT * FROM comment WHERE parentid=:id ORDER BY create_date",{'id':self.id})
        result = c.fetchall()
        for tempvalue in result:
            if(tempvalue['parentid'] == tempvalue['postid']):
                break
            tempcomment = Comment(tempvalue['postid'],tempvalue['content'],tempvalue['userid'],tempvalue['parentid'])
            tempcomment.id = tempvalue['id']
            tempcomment.create_date = tempvalue['create_date']
            tempcomment.init_comment_poster()
            tempcomment.init_children()
            self.children.append(tempcomment)


    def save_to_parent(self):
        pass


class Activity:
    def __init__(self, info, userid):
        self.info = info
        self.userid = userid
        self.create_date = None

    def save(self):
        c = g.db.cursor()
        self.create_date = datetime.datetime.now()
        c.execute("INSERT INTO activity(info,create_date,userid) VALUES (?,?,?)",\
                                (self.info, self.create_date,self.userid))
        self.id = c.lastrowid
        g.db.commit()

    @staticmethod
    def get_activities_byuserid(id, limit = configure.ActivityNUMBER_PER_PAGE, offset = 0):
        c = g.db.cursor()
        c.execute("SELECT * FROM activity ORDER BY create_date DESC LIMIT :limit OFFSET :offset",\
                                {"limit":limit,"offset":offset*limit})
        result = c.fetchall()
        activities = []
        for activity in result:
            tempac = Activity(activity['info'], activity['userid'])
            tempac.create_date = activity['create_date']
            tempac.id = activity['id']
            activities.append(tempac)
        return activities