8813deb19c6ee8c5aebdd60518171805b7229ce7
[oweals/karmaworld.git] / README.md
1 # KarmaWorld
2 __Description__: A django application for sharing and uploading class notes.
3
4 __Copyright__: FinalsClub, a 501c3 non-profit organization
5
6 __License__: GPLv3 except where otherwise noted
7
8 __Contact__: info@karmanotes.org
9
10 v3.0 of the karmanotes.org website from the FinalsClub Foundation
11
12 # Purpose
13
14 KarmaNotes is an online database of college lecture notes.  KarmaNotes empowers college students to participate in the free exchange of knowledge. 
15
16 # Pre-Installation
17
18 ## Code
19
20 Before doing anything, you'll need the code. Grab it from github.
21
22 Clone the project from the central repo using your github account:
23
24     git clone git@github.com:FinalsClub/karmaworld.git
25
26 If you aren't using a system setup for github, then grab the project with
27 this command instead:
28
29     git clone https://github.com/FinalsClub/karmaworld.git
30
31 Generally speaking, this will create a subdirectory called `karmaworld` under
32 the directory where the `git` command was run. This git repository directory
33 will be referred to herein as `{project_root}`.
34
35 There might be some confusion as the git repository's directory will likely be
36 called `karmaworld` (this is `{project_root}`), but there is also a `karmaworld`
37 directory underneath that (`{project_root}/karmaworld`) alongside files like
38 `fabfile.py` (`{project_root}/fabfile.py`) and `README.md`
39 (`{project_root}/README.md`).
40
41 ## External Service Dependencies
42
43 Notice: This software makes use of external third party services which require
44 accounts to access the service APIs. Without these third parties available,
45 this software may require considerable overhaul.
46
47 ### Filepicker
48 This software uses [Filepicker.io](https://www.inkfilepicker.com/) for uploading
49 files. This requires an account with Filepicker.
50
51 Filepicker requires an additional third party file hosting site where it may
52 send uploaded files. For this project, we have used Amazon S3.
53
54 Filepicker will provide an API key. This is needed by the software.
55
56 ### Amazon S3
57
58 #### for Filepicker
59 This software uses [Amazon S3](http://aws.amazon.com/s3/) as a third party file
60 hosting site. The primary use case is a destination for Filepicker files. The
61 software won't directly need any S3 information for this use case; it will be
62 provided directly to Filepicker.
63
64 #### for Static File hosting
65 A secondary use case for S3 is hosting static files. The software will need to
66 update static files on the S3 bucket. In this case, the software will need the
67 S3 bucket name, access key, and secret key.
68
69 The code assumes S3 is used for static files in a production environment. To
70 obviate the need for hosting static files through S3 (noting that it still might
71 be necessary for Filepicker), a workaround was explained [in this Github ticket](https://github.com/FinalsClub/karmaworld/issues/192#issuecomment-30193617).
72
73 That workaround is repeated here. Make the following changes to
74 `{project_root}/karmaworld/settings/prod.py`:
75
76 1. comment out everything about static_s3 from imports
77 2. comment out storages from the `INSTALLED_APPS`
78 3. change `STATIC_URL` to `'/assets/'`
79 4. comment out the entire storages section (save for part of `INSTALLED_APPS` and `STATIC_URL`)
80 5. add this to the nginx config:
81
82     location /assets/ {
83         root /var/www/karmaworld/karmaworld/;
84     }
85     
86 ### IndexDen
87 KarmaNotes uses IndexDen to create a searchable index of all the notes
88 in the system. Create an free IndexDen account at [their homepage](http://indexden.com/).
89 You will be given a private URL that accesses your IndexDen account.
90 Create a file at karmaworld/secret/indexden.py, and enter your private URL, and the name
91 of the index you want KarmaNotes to use. The index will be created automatically when
92 KarmaNotes is run if it doesn't already exist. For example,
93 ```
94 PRIVATE_URL = 'http://:secretsecret@secret.api.indexden.com'
95 INDEX = 'karmanotes_something_something'
96 ```
97
98 ### Google Drive
99 This software uses [Google Drive](https://developers.google.com/drive/) to
100 convert documents to and from various file formats.
101
102 A Google Drive service account with access to the Google Drive is required. Thismay be done with a Google Apps account with administrative privileges, or ask
103 your business sysadmin.
104
105 These are the instructions to create a Google Drive service account:
106 https://developers.google.com/drive/delegation
107
108 When completed, you'll have a file called `client_secrets.json` and a p12 file
109 which is the key to access the service account. Both are needed by the software.
110
111 ### Twitter
112
113 Twitter is used to post updates about new courses. Access to the Twitter API
114 will be required for this task.
115
116 If this Twitter feature is desired, the consumer key and secret as well as the
117 access token key and secret are needed by the software.
118
119 If the required files are not found, then no errors will occur.
120
121 To set this up, create a new Twitter application at https://dev.twitter.com/apps/new.
122 Make sure this application has read/write access. Generate an access token. Go to your
123 OAuth settings, and grab the "Consumer key", "Consumer secret", "Access token", and
124 "Access token secret".
125
126 Create a file at karmaworld/secret/twitter.py, and enter these tokens. For example,
127 ```
128 CONSUMER_KEY = '???'
129 CONSUMER_SECRET = '???'
130 ACCESS_TOKEN_KEY = '???'
131 ACCESS_TOKEN_SECRET = '???'
132 ```
133
134 # Development Install
135
136 If you need to setup the project for development, it is highly recommend that
137 you grab create a development virtual machine or (if available) grab one that
138 has already been created for your site.
139
140 The *host machine* is the system which runs e.g. VirtualBox, while the
141 *virtual machine* refers to the system running inside e.g. VirtualBox. 
142
143 ## Creating a Virtual Machine by hand
144
145 Create a virtual machine with your favorite VM software. Configure the virtual
146 machine for production with the steps shown in the [Production Install](#production-install) section.
147
148 ## Creating a Virtual Machine with Vagrant
149
150 Vagrant supports a variety of virtual machine software and there is additional
151 support for Vagrant to deploy to a wider variety. However, for these
152 instructions, it is assumed Vagrant will be deployed to VirtualBox.
153
154 1. Configure external dependencies on the host machine:
155    * Under `{project_root}/karmaworld/secret/`:
156         1. Copy files with the example extension to the corresponding filename
157           without the example extension (e.g.
158           `cp filepicker.py.example filepicker.py`)
159         1. Modify those files, but ignore `db_settings.py` (Vagrant takes care of that one)
160         1. Copy the Google Drive service account p12 file to `drive.p12`
161            (this filename and location may be changed in `drive.py`)
162         1. Ensure `*.py` in `secret/` are never added to the git repo.
163            (.gitignore should help warn against taking this action)
164
165 1. Install [VirtualBox](http://www.virtualbox.com/)
166
167 1. Install [vagrant](http://www.vagrantup.com/) 1.3 or higher
168
169 1. Use Vagrant to create the virtual machine.
170    * While in `cd {project_root}`, type `vagrant up`
171
172 1. Connect to the virtual machine with `vagrant ssh`
173
174 Note:
175 Port 80 of the virtual machine will be configured as port 6659 on the host
176 system. While on the host system, fire up your favorite browser and point it at
177 `http://localhost:6659/`. This connects to your host system on port 6659, which
178 forwards to your virtual machine's web site.
179
180 ## Completing the Virtual Machine with Fabric
181
182 *Notice* Fabric might not run properly if you presently in a virtualenv.
183 `deactivate` prior to running fab commands.
184
185 1. On the virtual machine, type `cd karmanotes` to get into the code repository.
186
187 1. In the code repo of the VM, type `fab -H 127.0.0.1 first_deploy`
188
189    During this process, you will be queried to create a Django site admin.
190    Provide information. You will be asked to remove duplicate schools. Respond
191    with yes.
192
193 # Production Install
194
195 These steps are taken care of by automatic utilities. Vagrant performs the
196 first subsection of these instructions and Fabric performs the second
197 subsection. These instructions are detailed here for good measure, but should
198 not generally be needed.
199
200 1. Ensure the following are installed:
201    * `git`
202    * `7zip` (for unzipping US Department of Education files)
203    * `PostgreSQL` (server and client)
204    * `nginx`
205    * `libxslt` and `libxml2` (used by some Python libraries)
206    * `RabbitMQ` (server)
207    * `memcached`
208    * `Python`
209    * `PIP`
210    * `virtualenv`
211    * `virtualenvwrapper` (might not be needed anymore)
212    * `pdf2htmlEX`
213
214    On a Debian system supporting Apt, this can be done with:
215 ```
216     sudo apt-get install python-pip postgresql python-virtualenv nginx \
217     virtualenvwrapper git libxml2-dev p7zip-full \
218     postgresql-server-dev-9.1 libxslt1-dev \
219     libmemcached-dev python-dev rabbitmq-server \
220     cmake libpng-dev libjpeg-dev libgtk2.0-dev \
221     pkg-config libfontconfig1-dev autoconf libtool
222
223     wget http://poppler.freedesktop.org/poppler-0.24.4.tar.xz
224     tar xf poppler-0.24.4.tar.gz
225     ./configure --prefix=/usr --enable-xpdf-headers
226     make
227     sudo make install
228
229     git clone https://github.com/fontforge/fontforge.git
230     ./autogen.sh
231     ./configure --prefix=/usr
232     make
233     sudo make install
234
235     git clone https://github.com/charlesconnell/pdf2htmlEX.git
236     cd pdf2htmlEX
237     cmake .
238     make
239     sudo make install
240 ```
241
242 1. Generate a PostgreSQL database and a role with read/write permissions.
243    * For Debian, these instructions are helpful: https://wiki.debian.org/PostgreSql
244
245 1. Modify configuration files.
246    * There are settings in `{project_root}/karmaworld/settings/prod.py`
247        * Most of the setting should work fine by default.
248    * There are additional configuration options for external dependencies
249      under `{project_root}/karmaworld/secret/`.
250         1. Copy files with the example extension to the corresponding filename
251           without the example extension (e.g.
252           `cp filepicker.py.example filepicker.py`)
253         1. Modify those files.
254            * Ensure `PROD_DB_USERNAME`, `PROD_DB_PASSWORD`, and `PROD_DB_NAME`
255              inside `db_settings.py` match the role, password, and database
256              generated in the previous step.
257         1. Copy the Google Drive service account p12 file to `drive.p12`
258            (this filename and location may be changed in `drive.py`)
259         1. Ensure `*.py` in `secret/` are never added to the git repo.
260            (.gitignore should help warn against taking this action)
261
262 1. Make sure that /var/www exists, is owned by the www-data group, and that
263    the desired user is a member of the www-data group.
264
265 1. Configure nginx with a `proxy_pass` to port 8000 (or whatever port gunicorn
266    will be running the site on) and any virtual hosting that is desired.
267    Here is an example server file to put into `/etc/nginx/sites-available/`
268
269         server {
270             listen 80;
271             # don't do virtual hosting, handle all requests regardless of header
272             server_name "";
273             client_max_body_size 20M;
274         
275             location / {
276                 # pass traffic through to gunicorn
277                 proxy_pass http://127.0.0.1:8000;
278             }
279         }
280
281 1. Configure the system to start supervisor on boot. An init script for
282    supervisor is in the repo at `{project_root}/karmaworld/confs/supervisor`.
283    `update-rc.d supervisor defaults` is the Debian command to load the init
284    script into the correct directories.
285
286 1. Make sure `{project_root)/var/log` and `{project_root}/var/run` exist and
287    may be written to, or else put the desired logging and run file paths into
288    `{project_root}/confs/prod/supervisord.conf`
289
290 1. Create a virtualenv under `/var/www/karmaworld/venv`
291
292 1. Change into the virtualenv with `. /var/www/karmaworld/venv/bin/activate`.
293    Within the virtualenv:
294
295     1. Update the Python depenencies with `pip -i {project_root}/reqs/prod.txt`
296         * If you want debugging on a production-like system:
297             1. run `pip -i {project_root}/reqs/vmdev.txt`
298             1. change `{project_root}/manage.py` to point at `vmdev.py`
299                instead of `prod.py`
300             1. ensure firefox is installed on the system (such as by
301                `sudo apt-get install firefox`)
302     
303     1. Setup the database with `python {project_root}/manage.py syncdb --migrate`
304
305     1. Collect static resources and put them in the static hosting location with
306        `python {project_root}/manage.py collect_static`
307
308 1. The database needs to be populated with schools. A list of accredited schools
309    may be found on the US Department of Education website:
310    http://ope.ed.gov/accreditation/GetDownloadFile.aspx
311
312    Alternatively, use the built-in scripts while in the virtualenv:
313
314    1. Fetch USDE schools with
315       `python {project_root}/manage.py fetch_usde_csv ./schools.csv`
316
317    1. Upload the schools into the database with
318       `python {project_root}/manage.py import_usde _csv ./schools.csv`
319
320    1. Clean up redundant information with
321       `python {project_root}/manage.py sanitize_usde_schools`
322
323 1. Startup `supervisor`, which will run `celery` and `gunicorn`. This may be
324    done from within the virtualenv by typing
325    `python {project_root}/manage.py start_supervisord`
326
327 1. If everything went well, gunicorn should be running the website on port 8000
328    and nginx should be serving gunicorn on port 80.
329
330 # Accessing the Vagrant Virtual Machine
331
332 ## Accessing the VM via Fabric
333 If you have Fabric on the host machine, you can configure your host machine
334 to run Fabric against the virtual machine.
335
336 You will need to setup the host machine with the proper SSH credentials to
337 access the virtual machine. This is done by running `vagrant ssh-config` from
338 `{project_root}`.
339
340 The VM will, by default, route its SSH connection through localhost port 2222
341 on the host machine and the base user with be vagrant. Point Fabric there when
342 running fab commands from `{project_root}`. So the command will look like this:
343
344         fab -H 127.0.0.1 --port=2222 -u vagrant <commands>
345
346 In unix, it might be convenient to create and use an alias like so:
347
348         alias vmfab='fab -H 127.0.0.1 --port=2222 -u vagrant'
349         vmfab <commands>
350
351 Removing a unix alias is done with `unalias`.
352
353 ## Connecting to the VM via SSH
354 If you have installed a virtual machine using `vagrant up`, you can connect
355 to it by running `vagrant ssh` from `{project_root}`.
356
357 ## Connecting to the development website on the VM
358 To access the website running on the VM, point your browser at
359 http://localhost:6659/ using your host computer.
360
361 Port 6659 on your local machine is set to forward to the VM's port 80.
362
363 Fun fact: 6659 was chosen because of OM (sanskrit) and KW (KarmaWorld) on a
364 phone: 66 59.
365
366 ## Updating the VM code repository
367 Once connected to the virtual machine by SSH, you will see `karmaworld` in
368 the home directory. That is the `{project_root}` in the virtual machine.
369
370 `cd karmaworld` and then use `git fetch; git merge` and/or `git pull origin` as
371 desired.
372
373 The virtual machine's code repository is set to use your host machine's
374 local repository as the origin. So if you make changes locally and commit them,
375 without pushing them anywhere, your VM can pull those changes in for testing.
376
377 This may seem like duplication. It is. The duplication allows your host machine
378 to maintain git credentials and manage repository access control so that your
379 virtual machine doesn't need sensitive information. Your virtual machine simply
380 pulls from the local repository on your local file system without needing
381 credentials, etc.
382
383 ## Deleting the Virtual Machine
384 If you want to start a fresh virtual machine or simply remove the virtual
385 machine from your hard drive, Vagrant has a command for that. While in 
386 `{project_root}` of the host system, type `vagrant destroy` and confirm with
387 `y`. This will remove the VM from your hard drive.
388
389 If you wanted a fresh VM, the next step is to run `vagrant up`, which will
390 start a brand new VM (since the old one is gone).
391
392 ## Other Vagrant commands
393 Please see [vagrant documentation](http://docs.vagrantup.com/v2/cli/index.html)
394 for more information on how to use the vagrant CLI to manage your development
395 VM.
396
397 # Django Database management
398
399 ## South
400
401 We have setup Django to use
402 [south](http://south.aeracode.org/wiki/QuickStartGuide) for migrations. When
403 changing models, it is important to run
404 `python {project_root}/manage.py schemamigration` which will create a migration
405  to reflect the model changes into the database. These changes can be pulled
406 into the database with `python {project_root}/manage.py migrate`.
407
408 Sometimes the database already has a migration performed on it, but that
409 information wasn't told to south. There are subtleties to the process which
410 require looking at the south docs. As a tip, start by looking at the `--fake`
411 flag.
412
413 # Assets from Third Parties
414
415 A number of assets have been added to the repository which come from external
416 sources. It would be difficult to keep a complete list in this README and keep
417 it up to date. Software which originally came from outside parties can
418 generally be found in `{project_root}/karmaworld/assets`.
419
420 Additionally, all third party Python projects (downloaded and installed with
421 pip) are listed in these files:
422
423 * `{project_root}/reqs/common.txt`
424 * `{project_root}/reqs/dev.txt`
425 * `{project_root}/reqs/prod.txt`
426 * `{project_root}/reqs/vmdev.txt` (just a combo of dev.txt and prod.txt)
427
428 # Thanks
429
430 * KarmaNotes.org is a project of the FinalsClub Foundation with generous funding from the William and Flora Hewlett Foundation
431
432 * Also thanks to [rdegges](https://github.com/rdegges/django-skel) for the django-skel template