summaryrefslogtreecommitdiff
path: root/tbc/views.py
blob: 7c3f43bd2e71ef81d6b459910857786a3eb7db4f (plain)
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
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.core.context_processors import csrf
from django.contrib.auth import authenticate, login, logout
from models import *
from tbc.forms import *
from local import *
import os
import zipfile
import StringIO
import smtplib
import shutil
from email.mime.text import MIMEText


def email_send(to,subject,msg):
	try:
		smtpObj = smtplib.SMTP('localhost')
		mail_from = "textbook@fosse.in"
		message = MIMEText(msg)
		message['Subject'] = subject
		message['From'] = mail_from
		message['to'] = to
		smtpObj.sendmail(mail_from, to, message.as_string())         
	except SMTPException:
		return HttpResponse("Error:unable to send email")

def Home(request):
    context = {}
    images = []
    if request.user.is_anonymous():
        context['user'] = None
    else:
        context['user'] = request.user
    books = Book.objects.filter(approved=True)[0:6]
    """if len(books)>=6:
        context['books'] = books
    else:
        books = Book.objects.all()
        context['books'] = books"""
    for book in books:
        images.append(ScreenShots.objects.filter(book=book)[0])
    context['images'] = images
    book_images = []
    for i in range(len(books)):
        obj = {'book':books[i], 'image':images[i]}
        book_images.append(obj)
    context['items'] = book_images
    return render_to_response('base.html', context)
    

def UserLogin(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        curr_user = authenticate(username=username, password=password)
        login(request, curr_user)
        try:
            Profile.objects.get(user=curr_user)
            return HttpResponseRedirect("/")
        except:
            return HttpResponseRedirect("/profile")
    else:
        form = UserLoginForm()
    context = {}
    context.update(csrf(request))
    context['form'] = form
    return render_to_response('tbc/login.html', context)


def UserRegister(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/login')
        else:
            context = {}
            context.update(csrf(request))
            context['form'] = form
            return render_to_response('tbc/register.html', context)
    else:
        form = UserRegisterForm()
    context = {}
    context.update(csrf(request))
    context['form'] = form
    return render_to_response('tbc/register.html', context)


def UserProfile(request):
    user = request.user
    if user.is_authenticated():
        if request.method == 'POST':
            form = UserProfileForm(request.POST)
            if form.is_valid():
                data = form.save(commit=False)
                data.user = request.user
                data.save()
                return HttpResponseRedirect('/')
            else:
                context = {}
                context.update(csrf(request))
                context['form'] = form
                return render_to_response('tbc/profile.html', context)
        else:
            form = UserProfileForm()
        context = {}
        context.update(csrf(request))
        context['form'] = form
        context['user'] = user
        return render_to_response('tbc/profile.html', context)
    else:
        return HttpResponse('invalid user')
        

def UserLogout(request):
    user = request.user
    if user.is_authenticated() and user.is_active:
        logout(request)
    return redirect('/')
    

def SubmitBook(request):
    curr_user = request.user
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            data = form.save(commit=False)
            profile = Profile.objects.get(user=request.user.id)
            data.contributor = profile
            data.save()
            return HttpResponseRedirect('/upload-content')
        else:
            context = {}
            context.update(csrf(request))
            context['form'] = form
            return render_to_response('tbc/submit-book.html', context)
    else:
        form = BookForm()
    context = {}
    context.update(csrf(request))
    context['form'] = form
    context['user'] = curr_user
    return render_to_response('tbc/submit-book.html', context)


def ContentUpload(request):
    user = request.user
    curr_book = Book.objects.order_by("-id")[0]
    if request.method == 'POST':
        for i in range(1, curr_book.no_chapters+1):
            chapter = Chapters()
            chapter.name = request.POST['chapter'+str(i)]
            chapter.notebook = request.FILES['notebook'+str(i)]
            chapter.book = curr_book
            chapter.save()
        for i in range(1, 4):
            screenshot = ScreenShots()
            screenshot.caption = request.POST['caption'+str(i)]
            screenshot.image = request.FILES['image'+str(i)]
            screenshot.book = curr_book
            screenshot.save()
        book = Book.objects.order_by("-id")[0]
        subject = "Python-TBC: Book Submission"
        message = "Hi "+curr_book.reviewer.name+",\n"+\
                  "A book has been submitted on the Python TBC interface.\n"+\
                  "Details of the Book & Contributor:\n"+\
                  "Contributor: "+curr_book.contributor.user.first_name+" "+curr_book.contributor.user.last_name+"\n"+\
                  "Book Title: "+curr_book.title+"\n"+\
                  "Author: "+curr_book.author+"\n"+\
                  "Publisher: "+curr_book.publisher_place+"\n"+\
                  "ISBN: "+curr_book.isbn+"\n"+\
                  "Follow the link to review the book: \n"+\
                  "http://dev.fossee.in/book-review/"+str(curr_book.id)
        email_send(book.reviewer.email, subject, message)
        return HttpResponseRedirect('/')
    context = {}
    context.update(csrf(request))
    context['user'] = user
    context['no_notebooks'] = [i for i in range(1, curr_book.no_chapters+1)]
    context['no_images'] = [i for i in range(1, 4)]
    return render_to_response('tbc/upload-content.html', context)


def generateZip(book_id):
    book = Book.objects.get(id=book_id)
    files_to_zip = []
    file_path = os.path.abspath(os.path.dirname(__file__))
    file_path = file_path+"/static/uploads/"
    notebooks = Chapters.objects.filter(book=book)
    for notebook in notebooks:
        files_to_zip.append(file_path+str(notebook.notebook))
    zip_subdir = book.title.strip()
    zipfile_name = "%s.zip" %zip_subdir
    s = StringIO.StringIO()
    zip_file = zipfile.ZipFile(s, 'w')
    for fpath in files_to_zip:
        fdir, fname = os.path.split(fpath)
        zip_path = os.path.join(book.title, fname)
        zip_file.write(fpath, zip_path)
    zip_file.close()
    return s, zipfile_name


def GetZip(request, book_id=None):
    user = request.user
    s, zipfile_name = generateZip(book_id)
    resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
    resp['Content-Disposition'] = 'attachment; filename=%s' % zipfile_name
    return resp


def BookDetails(request, book_id=None):
    context = {}
    if request.user.is_anonymous():
        context['user'] = None
    else:
        context['user'] = request.user
    book = Book.objects.get(id=book_id)
    chapters = Chapters.objects.filter(book=book)
    images = ScreenShots.objects.filter(book=book)
    context['chapters'] = chapters
    context['images'] = images
    context['book'] = book
    return render_to_response('tbc/book-details.html', context)
    

def BookReview(request, book_id=None):
    context = {}
    if book_id:
        book = Book.objects.get(id=book_id)
        chapters = Chapters.objects.filter(book=book)
        images = ScreenShots.objects.filter(book=book)
        context['chapters'] = chapters
        context['images'] = images
        #context['user'] = user
        context['book'] = book
        context.update(csrf(request))
        return render_to_response('tbc/book-review-details.html', context)
    else:
        books = Book.objects.filter(approved=False)
        context['books'] = books
        context.update(csrf(request))
        return render_to_response('tbc/book-review.html', context)


def ApproveBook(request, book_id=None):
    user = request.user
    context = {}
    if request.method == 'POST' and request.POST['approve_notify'] == "approve":
        book = Book.objects.get(id=book_id)
        book.approved = True
        book.save()
        file_path = os.path.abspath(os.path.dirname(__file__))
        zip_path = "/".join(file_path.split("/")[1:-2])
        zip_path = "/"+zip_path+"/Python-Textbook-Companions/"
        file_path = file_path+"/static/uploads/"
        directory = file_path+book.contributor.user.first_name
        os.chmod(directory, 0777)
        os.chdir(directory)
        fp = open(book.title+"/README.txt", 'w')
        fp.write("Contributed By: "+book.contributor.user.first_name+" "+book.contributor.user.last_name+"\n")
        fp.write("Course: "+book.contributor.course+"\n")
        fp.write("College/Institute/Organization: "+book.contributor.insti_org+"\n")
        fp.write("Department/Designation: "+book.contributor.dept_desg+"\n")
        fp.write("Book Title: "+book.title+"\n")
        fp.write("Author: "+book.author+"\n")
        fp.write("Publisher: "+book.publisher_place+"\n")
        fp.write("Year of publication: "+book.year_of_pub+"\n")
        fp.write("Isbn: "+book.isbn+"\n")
        fp.write("Edition: "+book.edition)
        fp.close()
        x = shutil.copytree(book.title, zip_path+book.title)
        context['user'] = user
        return HttpResponseRedirect("/book-review")
    elif request.method == 'POST' and request.POST['approve_notify'] == "notify":
        context['user'] = user
        book = Book.objects.get(id=book_id)
        subject = "Python-TBC: Book Submission"
        message = "Hi "+Book.reviewer.name+",\n"\
                  "A book has been submitted on the interface.\n"\
                  ""
        return HttpResponse("Mail Sent")
    else:
        context['user'] = user
        return HttpResponseRedirect("/book-review/"+book_id)

def BrowseBooks(request):
    context = {}
    if request.user.is_anonymous():
        context['user'] = None
    else:
        context['user'] = request.user
    images = []
    if request.method == 'POST':
        category = request.POST['category']
        books = Book.objects.filter(category=category)
        for book in books:
            images.append(ScreenShots.objects.filter(book=book)[0])
    else:
        category = 'computer science'
        books = Book.objects.filter(category='computer science')
        for book in books:
            images.append(ScreenShots.objects.filter(book=book)[0])
    context.update(csrf(request))
    book_images = []
    for i in range(len(books)):
        obj = {'book':books[i], 'image':images[i]}
        book_images.append(obj)
    context['items'] = book_images
    context['category'] = category
    return render_to_response('tbc/browse-books.html', context)