Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/app/app.py
blob: 40405cba1cf2cfd6db4a5709b14160d6db93ce0e (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
import os
import sys
from flask import flash,Flask,request,url_for,redirect,session
from flaskext.genshi import Genshi, render_response

app = Flask(__name__)
app.debug = True
app.secret_key="ilovesugar"
genshi = Genshi(app)

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

def list_files(directory):
    files=os.listdir(directory)
    print "showing %s" % directory
    return sorted(files)

def identify(filename):
    if not os.path.exists(filename):
        raise ValueError('File not found')
    icon = 'document-generic.png'
    mode = ''
    directory=os.path.dirname(filename) 
    icon = 'document-generic.png'
    href = '/edit/%s' % filename
    if filename.endswith('.py'):
        icon = 'text-x-python.png'
        mode = 'python'
    if filename.endswith('.html'):
        icon = 'text-uri-list.png'
        mode = 'html'
    if filename.endswith('.css'):
        icon = 'text-uri-list.png'
        mode = 'css'
    if filename.endswith('.js'):
        icon = 'text-uri-list.png'
        mode = 'javascript'
    if os.path.isdir(filename):
        icon = 'folder.png'
        href = '/files/%s' % filename 
        mode = 'dir'
    if filename.endswith('.xo'):
        href = '#'
    return icon,mode,href

@app.route('/')
def index():
    try:
        directory=session['pwd']
    except KeyError:
        directory=u""
    return vsplit(frame2="/files/%s" % directory)

@app.route('/edit/')
@app.route('/edit/<path:filename>')
def edit(filename):
    try:
        if len(session['edit_history'])==6:
            session['edit_history'].pop(0)
        if not filename in session['edit_history']:
            session['edit_history'].append(filename)
    except KeyError:
        session['edit_history']=[filename,]
    session.modified = True
    icon, mode, href = identify(filename)
    content = open(filename).read().decode('utf-8') 
    tmpl = 'editor.html'
    directory=os.path.dirname(filename) 
    return render_response(tmpl, dict(content=content, icon=icon,basename=os.path.basename(filename),
            filename=filename, absdir=os.path.normpath(directory), mode=mode, directory=directory))

@app.route('/save', methods=['POST'])
def save(): 
    filename = request.form['filename']
    f=open(filename,"wb")
    content = request.form['content']
    # Ace seems to be confused about newlines
    content = content.replace('\r\n', '\n').replace('\r', '\n') 
    f.write(content.encode('utf-8'))
    print "saving content: %s" % filename 
    f.close()
    directory = os.path.dirname(filename)
    return "saved"

@app.route('/chdir', methods=['POST'])
def chdir():
    if request.form['oldproject']!='':
        session['project_dir']=os.getenv('HOME')+'/Activities/'+request.form['oldproject']
        with open(session['project_dir']+"/activity/activity.info", 'r') as f:
            for line in f:
                if line.startswith('name'):
                    session['project_name']=line[7:-1]
        session['pwd']=session['project_home_dir']="."
        os.chdir(session['project_dir'])
        session['project_home']='/help'
        #session['edit_history']=[]
        if os.path.isdir('app'):
            session['pwd']=session['project_home_dir']='app'
            session['project_home']='/edit/app/app.py'
        elif os.path.isfile('activity.py'):
            session['project_home']='/edit/activity.py'
    return vsplit(frame1=session['project_home'],
                  frame2='/files/%s' % session['pwd'])

@app.route('/fileshome/')
def browse_home():
    try:
        home_dir = session['project_home_dir']
    except KeyError:
        home_dir = "."
    return browse(home_dir)

@app.route('/files/')
@app.route('/files/<path:directory>')
def browse(directory='.'):
    session['pwd']=directory
        
    filelist = list_files(directory)
    try:
        session['project_dir']
    except KeyError:
        filelist=[]
    files = []
    if not os.path.abspath(directory)==os.path.abspath("."):
        files.append( { 'name': '..',
                        'icon': 'folder.png',
                        'mode': 'dir',
                        'href': '/files/%s' % os.path.join(directory,"..") })
    for filename in sorted(filelist):
        icon, mode, href = identify(directory + "/" + filename)
        if filename.startswith('.'): #hidden files
            continue
        if filename.endswith('.pyc'): #lets ignore these
            continue
        files.append( { 'name': filename,
                        'icon': icon,
                        'mode': mode,
                        'href': href } )
    try:
        project_name=session['project_name']
    except KeyError:
        project_name='None';
    return render_response('filer.html', dict(files=files, 
                absdir=os.path.normpath(directory),
                width=len(files)*94+10,# 94px is each file and 10px margin
                project_name=project_name
                ))
                
@app.route('/delete/<path:filename>')
def delete(filename):
    os.unlink(filename)
    directory = os.path.dirname(filename)
    return help()

@app.route('/shutdown')
def shutdown():
    shutdown_server()
    return 'Goodbye'

@app.route('/help')
def help():
    port=request.environ.get('SERVER_PORT')
    files=list_files(os.getenv('HOME')+'/Activities')
    activities = []
    for file in files:
        if file.endswith("activity"):
            activities.append(file)
    files = []
    try:
        for filename in session['edit_history']:
            icon, mode, href = identify(filename)
            files.append( { 'name': os.path.basename(filename),
                            'icon': icon,
                            'mode': mode,
                            'href': href } )
    except:
        pass
    try:
        project_name=session['project_name']
    except KeyError:
        project_name='None';
    
    return render_response('help.html', dict(port=port, 
                                            activities=activities,
                                            project_name=project_name,
                                            edit_history=files))

def vsplit(frame1='/help', frame2='/files/'):
    return render_response('split-view.html', dict(frame1=frame1, frame2=frame2))

@app.route('/split')
def split():
    return vsplit()

@app.route('/debug')
def debug():
    raise Warning("This is a traceback of the Construct IDE environment. This is what you'll see when there's an error in your program or you manually raise an exception.") 

if __name__=="__main__":
    try:
        port=int(sys.argv[1])
    except IndexError:
        port=5000
        import webbrowser
        webbrowser.open("http://localhost:%s/" % port)
    #app.run(port=port) # for local only
    app.run(host='0.0.0.0', port=port) # open for all