repo
string | commit
string | message
string | diff
string |
---|---|---|---|
rbonvall/grasp-crew-scheduling
|
fc9c3c822538ee401c45b30874ecb75ea32e2631
|
Fancy color debugging data for greedy construction
|
diff --git a/grasp.py b/grasp.py
index 1482f8b..84de028 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,70 +1,87 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
range = xrange
def DEBUG(s): print s
+def DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost):
+ data = (len(rotations), len(rcl), min_cost, max_cost)
+ DEBUG('#rotations: %d, #rcl: %d, min_cost: %d, max_cost: %d' % data)
+ rotation_reprs = []
+ for r in rotations:
+ r_repr = '%s:%d' % (str(r.tasks), greedy_cost(r))
+ if r in rcl:
+ c = int(r == selected_rotation)
+ if greedy_cost(r) == min_cost:
+ r_repr = '\033[%d;40;32m%s\033[0m' % (c, r_repr)
+ else:
+ r_repr = '\033[%d;40;36m%s\033[0m' % (c, r_repr)
+ if greedy_cost(r) == max_cost:
+ r_repr = '\033[0;40;31m%s\033[0m' % r_repr
+ rotation_reprs.append(r_repr)
+ DEBUG(' '.join(rotation_reprs))
+
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost):
rotations = rotations[:]
solution = []
alpha = 0.8
while True:
min_cost = greedy_cost(min(rotations, key=greedy_cost))
max_cost = greedy_cost(max(rotations, key=greedy_cost))
threshold = min_cost + alpha * (max_cost - min_cost)
#rcl = sorted(rotations, key=greedy_cost)[:10]
rcl = [r for r in rotations if greedy_cost(r) < threshold]
selected_rotation = choice(rcl)
- DEBUG('Selection from RCL: %s' % str(selected_rotation))
solution.append(selected_rotation)
+ DEBUG_RCL(rotations, rcl, selected_rotation, min_cost, max_cost, greedy_cost)
+
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
- DEBUG('%d candidates remaining' % len(rotations))
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
greedy_cost = partial(rotation_cost,
per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
07b022b5d5595a5c1757f4a613d0fdc68be103fe
|
RCL alpha parameter implementation
|
diff --git a/grasp.py b/grasp.py
index cca0b28..1482f8b 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,65 +1,70 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice, random
from functools import partial
range = xrange
def DEBUG(s): print s
def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
"""Cost of adding a rotation to a solution"""
return (-per_task_bonification * len(r.tasks) +
perturbation_radius * random() +
r.cost)
def construct_solution(rotations, csp, greedy_cost):
rotations = rotations[:]
solution = []
+ alpha = 0.8
while True:
- rcl = sorted(rotations, key=greedy_cost)[:10]
+ min_cost = greedy_cost(min(rotations, key=greedy_cost))
+ max_cost = greedy_cost(max(rotations, key=greedy_cost))
+ threshold = min_cost + alpha * (max_cost - min_cost)
+ #rcl = sorted(rotations, key=greedy_cost)[:10]
+ rcl = [r for r in rotations if greedy_cost(r) < threshold]
selected_rotation = choice(rcl)
DEBUG('Selection from RCL: %s' % str(selected_rotation))
solution.append(selected_rotation)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
DEBUG('%d candidates remaining' % len(rotations))
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
greedy_cost = partial(rotation_cost,
per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
f702e0aa58ca8c2405b1cfe5aefec4f68b12d740
|
chmod +x csp.py grasp.py
|
diff --git a/csp.py b/csp.py
old mode 100644
new mode 100755
diff --git a/grasp.py b/grasp.py
old mode 100644
new mode 100755
|
rbonvall/grasp-crew-scheduling
|
3d8f2fef21f9524b442c26c84a4b1d570fcf2447
|
Generic greedy cost function
|
diff --git a/grasp.py b/grasp.py
index 6054ede..cca0b28 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,66 +1,65 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
-from random import choice
+from random import choice, random
+from functools import partial
range = xrange
-# parameter for greedy cost function
-per_task_bonification = 300
-
def DEBUG(s): print s
-def element_cost(r):
- """Cost of adding an element to a solution"""
- return -per_task_bonification * len(r.tasks) + r.cost
+def rotation_cost(r, per_task_bonification=0, perturbation_radius=0):
+ """Cost of adding a rotation to a solution"""
+ return (-per_task_bonification * len(r.tasks) +
+ perturbation_radius * random() +
+ r.cost)
-def construct_solution(rotations, csp):
- # make a copy to use 2nd column as marginal cost
+def construct_solution(rotations, csp, greedy_cost):
rotations = rotations[:]
-
- R = len(rotations)
solution = []
while True:
- rcl = sorted(rotations, key=lambda r: element_cost(r))[:10]
+ rcl = sorted(rotations, key=greedy_cost)[:10]
selected_rotation = choice(rcl)
DEBUG('Selection from RCL: %s' % str(selected_rotation))
solution.append(selected_rotation)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
DEBUG('%d candidates remaining' % len(rotations))
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
+ greedy_cost = partial(rotation_cost,
+ per_task_bonification=300, perturbation_radius=0)
best_solution = None
for i in range(max_iterations):
- solution = construct_solution(rotations, csp)
+ solution = construct_solution(rotations, csp, greedy_cost)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
3cec9bcdc0c52c5ec24d9eb869bced128685ef00
|
Problem file as command line arg
|
diff --git a/grasp.py b/grasp.py
index c69356b..6054ede 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,62 +1,66 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice
range = xrange
# parameter for greedy cost function
per_task_bonification = 300
def DEBUG(s): print s
def element_cost(r):
"""Cost of adding an element to a solution"""
return -per_task_bonification * len(r.tasks) + r.cost
def construct_solution(rotations, csp):
# make a copy to use 2nd column as marginal cost
rotations = rotations[:]
R = len(rotations)
solution = []
while True:
rcl = sorted(rotations, key=lambda r: element_cost(r))[:10]
selected_rotation = choice(rcl)
DEBUG('Selection from RCL: %s' % str(selected_rotation))
solution.append(selected_rotation)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
DEBUG('%d candidates remaining' % len(rotations))
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
- filename = "orlib/csp50.txt"
+ import sys
+ try:
+ filename = sys.argv[1]
+ except IndexError:
+ filename = 'orlib/csp50.txt'
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
2072cfd5ec019fc12b953d54cecc3b42e3bf3b5a
|
Debug message with tells solution size
|
diff --git a/grasp.py b/grasp.py
index 3c6989f..c69356b 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,62 +1,62 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice
range = xrange
# parameter for greedy cost function
per_task_bonification = 300
def DEBUG(s): print s
def element_cost(r):
"""Cost of adding an element to a solution"""
return -per_task_bonification * len(r.tasks) + r.cost
def construct_solution(rotations, csp):
# make a copy to use 2nd column as marginal cost
rotations = rotations[:]
R = len(rotations)
solution = []
while True:
rcl = sorted(rotations, key=lambda r: element_cost(r))[:10]
selected_rotation = choice(rcl)
DEBUG('Selection from RCL: %s' % str(selected_rotation))
solution.append(selected_rotation)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
DEBUG('%d candidates remaining' % len(rotations))
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
- DEBUG('SOLUTION DONE:')
+ DEBUG('SOLUTION WITH %d ROTATIONS:' % len(solution))
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
filename = "orlib/csp50.txt"
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
22fc643eeebd2dda52c39a58665bb22b1a03ee66
|
Greedy cost takes nr of tasks into account
|
diff --git a/grasp.py b/grasp.py
index bf9070e..3c6989f 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,59 +1,62 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
from random import choice
range = xrange
+# parameter for greedy cost function
+per_task_bonification = 300
+
def DEBUG(s): print s
def element_cost(r):
"""Cost of adding an element to a solution"""
- return r.cost
+ return -per_task_bonification * len(r.tasks) + r.cost
def construct_solution(rotations, csp):
# make a copy to use 2nd column as marginal cost
rotations = rotations[:]
R = len(rotations)
solution = []
while True:
rcl = sorted(rotations, key=lambda r: element_cost(r))[:10]
selected_rotation = choice(rcl)
DEBUG('Selection from RCL: %s' % str(selected_rotation))
solution.append(selected_rotation)
# reevaluate candidates
rotations = [r for r in rotations
if not (r.tasks & selected_rotation.tasks)]
DEBUG('%d candidates remaining' % len(rotations))
if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
DEBUG('SOLUTION DONE:')
for r in solution: print r.tasks,
print
break
if not rotations:
DEBUG('NOT A FEASIBLE SOLUTION')
break
return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
filename = "orlib/csp50.txt"
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
c4d4cd19c8221842d28cad7d973eb1d51316e5c4
|
Greedy construction prototype
|
diff --git a/grasp.py b/grasp.py
index 49518a1..bf9070e 100644
--- a/grasp.py
+++ b/grasp.py
@@ -1,29 +1,59 @@
#!/usr/bin/env python
from csp import CrewSchedulingProblem
+from random import choice
range = xrange
+def DEBUG(s): print s
+
+def element_cost(r):
+ """Cost of adding an element to a solution"""
+ return r.cost
+
def construct_solution(rotations, csp):
- pass
+ # make a copy to use 2nd column as marginal cost
+ rotations = rotations[:]
+
+ R = len(rotations)
+ solution = []
+ while True:
+ rcl = sorted(rotations, key=lambda r: element_cost(r))[:10]
+ selected_rotation = choice(rcl)
+ DEBUG('Selection from RCL: %s' % str(selected_rotation))
+ solution.append(selected_rotation)
+
+ # reevaluate candidates
+ rotations = [r for r in rotations
+ if not (r.tasks & selected_rotation.tasks)]
+ DEBUG('%d candidates remaining' % len(rotations))
+ if sum(map(len, [r.tasks for r in solution])) == len(csp.tasks):
+ DEBUG('SOLUTION DONE:')
+ for r in solution: print r.tasks,
+ print
+ break
+ if not rotations:
+ DEBUG('NOT A FEASIBLE SOLUTION')
+ break
+ return solution
def local_search(solution):
return solution
def grasp(rotations, csp, max_iterations=1):
best_solution = None
for i in range(max_iterations):
solution = construct_solution(rotations, csp)
solution = local_search(solution)
best_solution = solution
break
return best_solution
def main():
filename = "orlib/csp50.txt"
csp = CrewSchedulingProblem(open(filename))
rotations = list(csp.generate_rotations())
solution = grasp(rotations, csp)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
cb736c7c8f8d124b197df92fbcb903a564c2b96b
|
set -> frozenset in Rotation
|
diff --git a/csp.py b/csp.py
index fa9feab..7777766 100644
--- a/csp.py
+++ b/csp.py
@@ -1,94 +1,94 @@
#!/usr/bin/env python
from collections import defaultdict
from itertools import izip as zip
range = xrange
try:
from collections import namedtuple
except ImportError:
from namedtuple import namedtuple
Task = namedtuple('Task', ['start', 'finish'])
Rotation = namedtuple('Rotation', ['tasks', 'cost', 'duration'])
# hack for nice set printing
-class set(set):
+class frozenset(frozenset):
__repr__ = lambda self: '{%s}' % str.join(', ', map(str, sorted(self)))
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
self.tasks = [Task(*t) for t in file_contents[:nr_tasks]]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
def generate_rotations(self, from_rotation=()):
if from_rotation:
candidates = self.possible_transitions[from_rotation[-1]]
else:
candidates = range(len(self.tasks))
for task in candidates:
rotation = from_rotation + (task,)
start_time = self.tasks[rotation[0]].start
finish_time = self.tasks[rotation[-1]].finish
duration = finish_time - start_time
if duration > self.time_limit:
continue
cost = sum(self.transition_costs[t] for t in zip(rotation, rotation[1:]))
- yield Rotation(set(rotation), cost, duration)
+ yield Rotation(frozenset(rotation), cost, duration)
for r in self.generate_rotations(rotation):
yield r
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
print
try:
from ptable import Table
except ImportError:
pass
else:
t = Table(csp.generate_rotations())
t.headers = ('Rotation', 'Cost', 'Duration')
t.align = 'lrr'
t.col_separator = ' | '
t.repeat_headers_after = 25
t.header_separator = True
t.print_table()
print '# of rotations: %d' % (len(t.data))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
f37c737aad46b3314a0686dfbb9ed476a78703ce
|
GRASP outline
|
diff --git a/grasp.py b/grasp.py
new file mode 100644
index 0000000..49518a1
--- /dev/null
+++ b/grasp.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+
+from csp import CrewSchedulingProblem
+range = xrange
+
+def construct_solution(rotations, csp):
+ pass
+
+def local_search(solution):
+ return solution
+
+def grasp(rotations, csp, max_iterations=1):
+ best_solution = None
+ for i in range(max_iterations):
+ solution = construct_solution(rotations, csp)
+ solution = local_search(solution)
+ best_solution = solution
+ break
+ return best_solution
+
+def main():
+ filename = "orlib/csp50.txt"
+ csp = CrewSchedulingProblem(open(filename))
+ rotations = list(csp.generate_rotations())
+ solution = grasp(rotations, csp)
+
+if __name__ == '__main__':
+ main()
+
|
rbonvall/grasp-crew-scheduling
|
d4f18c615d03de8366cc80bce9c790bdf1f6724d
|
Hack for a nicer set visualization
|
diff --git a/csp.py b/csp.py
index 60595e9..fa9feab 100644
--- a/csp.py
+++ b/csp.py
@@ -1,90 +1,94 @@
#!/usr/bin/env python
from collections import defaultdict
from itertools import izip as zip
range = xrange
try:
from collections import namedtuple
except ImportError:
from namedtuple import namedtuple
Task = namedtuple('Task', ['start', 'finish'])
Rotation = namedtuple('Rotation', ['tasks', 'cost', 'duration'])
+# hack for nice set printing
+class set(set):
+ __repr__ = lambda self: '{%s}' % str.join(', ', map(str, sorted(self)))
+
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
self.tasks = [Task(*t) for t in file_contents[:nr_tasks]]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
def generate_rotations(self, from_rotation=()):
if from_rotation:
candidates = self.possible_transitions[from_rotation[-1]]
else:
candidates = range(len(self.tasks))
for task in candidates:
rotation = from_rotation + (task,)
start_time = self.tasks[rotation[0]].start
finish_time = self.tasks[rotation[-1]].finish
duration = finish_time - start_time
if duration > self.time_limit:
continue
cost = sum(self.transition_costs[t] for t in zip(rotation, rotation[1:]))
yield Rotation(set(rotation), cost, duration)
for r in self.generate_rotations(rotation):
yield r
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
print
try:
from ptable import Table
except ImportError:
pass
else:
t = Table(csp.generate_rotations())
t.headers = ('Rotation', 'Cost', 'Duration')
t.align = 'lrr'
t.col_separator = ' | '
t.repeat_headers_after = 25
t.header_separator = True
t.print_table()
print '# of rotations: %d' % (len(t.data))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
1b5790d484132f30f07bb2e721146e980d5826cf
|
Rotation tasks as set, not tuple
|
diff --git a/csp.py b/csp.py
index f4fb21e..60595e9 100644
--- a/csp.py
+++ b/csp.py
@@ -1,91 +1,90 @@
#!/usr/bin/env python
from collections import defaultdict
from itertools import izip as zip
range = xrange
try:
from collections import namedtuple
except ImportError:
from namedtuple import namedtuple
Task = namedtuple('Task', ['start', 'finish'])
Rotation = namedtuple('Rotation', ['tasks', 'cost', 'duration'])
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
self.tasks = [Task(*t) for t in file_contents[:nr_tasks]]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
def generate_rotations(self, from_rotation=()):
if from_rotation:
candidates = self.possible_transitions[from_rotation[-1]]
else:
candidates = range(len(self.tasks))
for task in candidates:
rotation = from_rotation + (task,)
start_time = self.tasks[rotation[0]].start
finish_time = self.tasks[rotation[-1]].finish
duration = finish_time - start_time
if duration > self.time_limit:
continue
- print "***", rotation
cost = sum(self.transition_costs[t] for t in zip(rotation, rotation[1:]))
- yield Rotation(rotation, cost, duration)
+ yield Rotation(set(rotation), cost, duration)
for r in self.generate_rotations(rotation):
yield r
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
print
try:
from ptable import Table
except ImportError:
pass
else:
t = Table(csp.generate_rotations())
t.headers = ('Rotation', 'Cost', 'Duration')
t.align = 'lrr'
t.col_separator = ' | '
t.repeat_headers_after = 25
t.header_separator = True
t.print_table()
print '# of rotations: %d' % (len(t.data))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
15b64d66d4a86e9329910fc8d6ab6781491c0f6c
|
rm data lista
|
diff --git a/csp.py b/csp.py
index 020be7f..f4fb21e 100644
--- a/csp.py
+++ b/csp.py
@@ -1,92 +1,91 @@
#!/usr/bin/env python
from collections import defaultdict
from itertools import izip as zip
range = xrange
try:
from collections import namedtuple
except ImportError:
from namedtuple import namedtuple
Task = namedtuple('Task', ['start', 'finish'])
Rotation = namedtuple('Rotation', ['tasks', 'cost', 'duration'])
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
self.tasks = [Task(*t) for t in file_contents[:nr_tasks]]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
def generate_rotations(self, from_rotation=()):
if from_rotation:
candidates = self.possible_transitions[from_rotation[-1]]
else:
candidates = range(len(self.tasks))
for task in candidates:
rotation = from_rotation + (task,)
start_time = self.tasks[rotation[0]].start
finish_time = self.tasks[rotation[-1]].finish
duration = finish_time - start_time
if duration > self.time_limit:
continue
print "***", rotation
cost = sum(self.transition_costs[t] for t in zip(rotation, rotation[1:]))
yield Rotation(rotation, cost, duration)
for r in self.generate_rotations(rotation):
yield r
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
+ print
- # test generation of rotations
- data = []
try:
from ptable import Table
except ImportError:
pass
else:
t = Table(csp.generate_rotations())
t.headers = ('Rotation', 'Cost', 'Duration')
t.align = 'lrr'
t.col_separator = ' | '
t.repeat_headers_after = 25
t.header_separator = True
t.print_table()
print '# of rotations: %d' % (len(t.data))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
592a9ac1caac40d0982cf1c6569bef900fb11e33
|
Rotation as namedtuple, with cost and duration
|
diff --git a/csp.py b/csp.py
index 6317c19..020be7f 100644
--- a/csp.py
+++ b/csp.py
@@ -1,95 +1,92 @@
#!/usr/bin/env python
from collections import defaultdict
+from itertools import izip as zip
range = xrange
try:
from collections import namedtuple
except ImportError:
from namedtuple import namedtuple
Task = namedtuple('Task', ['start', 'finish'])
+Rotation = namedtuple('Rotation', ['tasks', 'cost', 'duration'])
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
self.tasks = [Task(*t) for t in file_contents[:nr_tasks]]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
def generate_rotations(self, from_rotation=()):
if from_rotation:
candidates = self.possible_transitions[from_rotation[-1]]
else:
candidates = range(len(self.tasks))
for task in candidates:
rotation = from_rotation + (task,)
start_time = self.tasks[rotation[0]].start
finish_time = self.tasks[rotation[-1]].finish
- if finish_time - start_time > self.time_limit:
+ duration = finish_time - start_time
+ if duration > self.time_limit:
continue
-
- yield rotation
+ print "***", rotation
+ cost = sum(self.transition_costs[t] for t in zip(rotation, rotation[1:]))
+ yield Rotation(rotation, cost, duration)
+
for r in self.generate_rotations(rotation):
yield r
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
# test generation of rotations
data = []
- for n, rotation in enumerate(csp.generate_rotations()):
- cost = sum(csp.transition_costs[t] for t in zip(rotation, rotation[1:]))
- start_time, _ = csp.tasks[rotation[0]]
- _, finish_time = csp.tasks[rotation[-1]]
- duration = finish_time - start_time
- r = str(tuple(x+1 for x in rotation))
- data.append((r, cost, duration))
-
try:
from ptable import Table
except ImportError:
pass
else:
- t = Table(data)
+ t = Table(csp.generate_rotations())
t.headers = ('Rotation', 'Cost', 'Duration')
t.align = 'lrr'
t.col_separator = ' | '
t.repeat_headers_after = 25
t.header_separator = True
t.print_table()
- print '# of rotations: %d' % (n + 1)
+ print '# of rotations: %d' % (len(t.data))
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
52e71156d0a9e4be99beafba8772acc32c0253c1
|
Gitignore vim swap files
|
diff --git a/.gitignore b/.gitignore
index 8f9be5c..eb5f003 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
*.pyc
ptable.py
+.*.swp
|
rbonvall/grasp-crew-scheduling
|
7605b0290324f08eba5a5a2178bdd74268c99cab
|
Namedtuple support for python < 2.6
|
diff --git a/csp.py b/csp.py
index 67af2f7..6317c19 100644
--- a/csp.py
+++ b/csp.py
@@ -1,92 +1,95 @@
#!/usr/bin/env python
from collections import defaultdict
range = xrange
-from collections import namedtuple
+try:
+ from collections import namedtuple
+except ImportError:
+ from namedtuple import namedtuple
Task = namedtuple('Task', ['start', 'finish'])
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
self.tasks = [Task(*t) for t in file_contents[:nr_tasks]]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
def generate_rotations(self, from_rotation=()):
if from_rotation:
candidates = self.possible_transitions[from_rotation[-1]]
else:
candidates = range(len(self.tasks))
for task in candidates:
rotation = from_rotation + (task,)
start_time = self.tasks[rotation[0]].start
finish_time = self.tasks[rotation[-1]].finish
if finish_time - start_time > self.time_limit:
continue
yield rotation
for r in self.generate_rotations(rotation):
yield r
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
# test generation of rotations
data = []
for n, rotation in enumerate(csp.generate_rotations()):
cost = sum(csp.transition_costs[t] for t in zip(rotation, rotation[1:]))
start_time, _ = csp.tasks[rotation[0]]
_, finish_time = csp.tasks[rotation[-1]]
duration = finish_time - start_time
r = str(tuple(x+1 for x in rotation))
data.append((r, cost, duration))
try:
from ptable import Table
except ImportError:
pass
else:
t = Table(data)
t.headers = ('Rotation', 'Cost', 'Duration')
t.align = 'lrr'
t.col_separator = ' | '
t.repeat_headers_after = 25
t.header_separator = True
t.print_table()
print '# of rotations: %d' % (n + 1)
if __name__ == '__main__':
main()
diff --git a/namedtuple.py b/namedtuple.py
new file mode 100644
index 0000000..7a5d392
--- /dev/null
+++ b/namedtuple.py
@@ -0,0 +1,103 @@
+# Copied from Python 2.6's collections module
+
+from operator import itemgetter as _itemgetter
+from keyword import iskeyword as _iskeyword
+import sys as _sys
+
+def namedtuple(typename, field_names, verbose=False):
+ """Returns a new subclass of tuple with named fields.
+
+ >>> Point = namedtuple('Point', 'x y')
+ >>> Point.__doc__ # docstring for the new class
+ 'Point(x, y)'
+ >>> p = Point(11, y=22) # instantiate with positional args or keywords
+ >>> p[0] + p[1] # indexable like a plain tuple
+ 33
+ >>> x, y = p # unpack like a regular tuple
+ >>> x, y
+ (11, 22)
+ >>> p.x + p.y # fields also accessable by name
+ 33
+ >>> d = p._asdict() # convert to a dictionary
+ >>> d['x']
+ 11
+ >>> Point(**d) # convert from a dictionary
+ Point(x=11, y=22)
+ >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
+ Point(x=100, y=22)
+
+ """
+
+ # Parse and validate the field names. Validation serves two purposes,
+ # generating informative error messages and preventing template injection attacks.
+ if isinstance(field_names, basestring):
+ field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
+ field_names = tuple(map(str, field_names))
+ for name in (typename,) + field_names:
+ if not all(c.isalnum() or c=='_' for c in name):
+ raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
+ if _iskeyword(name):
+ raise ValueError('Type names and field names cannot be a keyword: %r' % name)
+ if name[0].isdigit():
+ raise ValueError('Type names and field names cannot start with a number: %r' % name)
+ seen_names = set()
+ for name in field_names:
+ if name.startswith('_'):
+ raise ValueError('Field names cannot start with an underscore: %r' % name)
+ if name in seen_names:
+ raise ValueError('Encountered duplicate field name: %r' % name)
+ seen_names.add(name)
+
+ # Create and fill-in the class template
+ numfields = len(field_names)
+ argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
+ reprtxt = ', '.join('%s=%%r' % name for name in field_names)
+ dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
+ template = '''class %(typename)s(tuple):
+ '%(typename)s(%(argtxt)s)' \n
+ __slots__ = () \n
+ _fields = %(field_names)r \n
+ def __new__(cls, %(argtxt)s):
+ return tuple.__new__(cls, (%(argtxt)s)) \n
+ @classmethod
+ def _make(cls, iterable, new=tuple.__new__, len=len):
+ 'Make a new %(typename)s object from a sequence or iterable'
+ result = new(cls, iterable)
+ if len(result) != %(numfields)d:
+ raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
+ return result \n
+ def __repr__(self):
+ return '%(typename)s(%(reprtxt)s)' %% self \n
+ def _asdict(t):
+ 'Return a new dict which maps field names to their values'
+ return {%(dicttxt)s} \n
+ def _replace(self, **kwds):
+ 'Return a new %(typename)s object replacing specified fields with new values'
+ result = self._make(map(kwds.pop, %(field_names)r, self))
+ if kwds:
+ raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
+ return result \n
+ def __getnewargs__(self):
+ return tuple(self) \n\n''' % locals()
+ for i, name in enumerate(field_names):
+ template += ' %s = property(itemgetter(%d))\n' % (name, i)
+ if verbose:
+ print template
+
+ # Execute the template string in a temporary namespace and
+ # support tracing utilities by setting a value for frame.f_globals['__name__']
+ namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename)
+ try:
+ exec template in namespace
+ except SyntaxError, e:
+ raise SyntaxError(e.message + ':\n' + template)
+ result = namespace[typename]
+
+ # For pickling to work, the __module__ variable needs to be set to the frame
+ # where the named tuple is created. Bypass this step in enviroments where
+ # sys._getframe is not defined (Jython for example).
+ if hasattr(_sys, '_getframe'):
+ result.__module__ = _sys._getframe(1).f_globals['__name__']
+
+ return result
+
|
rbonvall/grasp-crew-scheduling
|
78f0af46aa22d40c4e49128c0c18a6f8a2f4f185
|
Namedtuple for tasks (python2.6)
|
diff --git a/csp.py b/csp.py
index ca91c2e..67af2f7 100644
--- a/csp.py
+++ b/csp.py
@@ -1,89 +1,92 @@
#!/usr/bin/env python
from collections import defaultdict
range = xrange
+from collections import namedtuple
+
+Task = namedtuple('Task', ['start', 'finish'])
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
- self.tasks = file_contents[:nr_tasks]
+ self.tasks = [Task(*t) for t in file_contents[:nr_tasks]]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
def generate_rotations(self, from_rotation=()):
if from_rotation:
candidates = self.possible_transitions[from_rotation[-1]]
else:
candidates = range(len(self.tasks))
for task in candidates:
rotation = from_rotation + (task,)
- start_time, _ = self.tasks[rotation[0]]
- _, finish_time = self.tasks[rotation[-1]]
+ start_time = self.tasks[rotation[0]].start
+ finish_time = self.tasks[rotation[-1]].finish
if finish_time - start_time > self.time_limit:
continue
yield rotation
for r in self.generate_rotations(rotation):
yield r
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
# test generation of rotations
data = []
for n, rotation in enumerate(csp.generate_rotations()):
cost = sum(csp.transition_costs[t] for t in zip(rotation, rotation[1:]))
start_time, _ = csp.tasks[rotation[0]]
_, finish_time = csp.tasks[rotation[-1]]
duration = finish_time - start_time
r = str(tuple(x+1 for x in rotation))
data.append((r, cost, duration))
try:
from ptable import Table
except ImportError:
pass
else:
t = Table(data)
t.headers = ('Rotation', 'Cost', 'Duration')
t.align = 'lrr'
t.col_separator = ' | '
t.repeat_headers_after = 25
t.header_separator = True
t.print_table()
print '# of rotations: %d' % (n + 1)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
088180b39ff8663aa93e763aa208c1e8260c4784
|
Gitignore Python bytecode and helper module
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8f9be5c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+*.pyc
+ptable.py
|
rbonvall/grasp-crew-scheduling
|
102ba5f474767eb1a2b911b88908ce738348d03d
|
Rotation generation method
|
diff --git a/csp.py b/csp.py
index 3d29ea1..ca91c2e 100644
--- a/csp.py
+++ b/csp.py
@@ -1,47 +1,89 @@
#!/usr/bin/env python
from collections import defaultdict
+range = xrange
class CrewSchedulingProblem:
"""Crew Scheduling problem instance from ORLIB."""
def __init__(self, input_file):
file_contents = [tuple(map(int, line.split())) for line in input_file]
nr_tasks, time_limit = file_contents.pop(0)
self.time_limit = time_limit
self.tasks = file_contents[:nr_tasks]
self.transition_costs = defaultdict(lambda: float('inf'))
self.possible_transitions = [list() for task in self.tasks]
for i, j, cost in file_contents[nr_tasks:]:
# Reindex to start from 0, not from 1 as in ORLIB instances
self.transition_costs[i - 1, j - 1] = cost
self.possible_transitions[i - 1].append(j - 1)
+ def generate_rotations(self, from_rotation=()):
+ if from_rotation:
+ candidates = self.possible_transitions[from_rotation[-1]]
+ else:
+ candidates = range(len(self.tasks))
+
+ for task in candidates:
+ rotation = from_rotation + (task,)
+ start_time, _ = self.tasks[rotation[0]]
+ _, finish_time = self.tasks[rotation[-1]]
+ if finish_time - start_time > self.time_limit:
+ continue
+
+ yield rotation
+ for r in self.generate_rotations(rotation):
+ yield r
+
+
def main():
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-':
problem_file = sys.stdin
else:
try:
problem_file = open(sys.argv[1])
except IOError:
sys.stderr.write("Couldn't open file %s\n" % problem_file)
sys.exit(-1)
csp = CrewSchedulingProblem(problem_file)
if problem_file == sys.stdin:
print '--- Problem from stdin ---'
else:
print '--- Problem: %s ---' % (sys.argv[1])
print 'Problem size: %d' % len(csp.tasks)
print 'Time limit: %d ' % csp.time_limit
print 'Transitions: %d ' % len(csp.transition_costs)
+ # test generation of rotations
+ data = []
+ for n, rotation in enumerate(csp.generate_rotations()):
+ cost = sum(csp.transition_costs[t] for t in zip(rotation, rotation[1:]))
+ start_time, _ = csp.tasks[rotation[0]]
+ _, finish_time = csp.tasks[rotation[-1]]
+ duration = finish_time - start_time
+ r = str(tuple(x+1 for x in rotation))
+ data.append((r, cost, duration))
+
+ try:
+ from ptable import Table
+ except ImportError:
+ pass
+ else:
+ t = Table(data)
+ t.headers = ('Rotation', 'Cost', 'Duration')
+ t.align = 'lrr'
+ t.col_separator = ' | '
+ t.repeat_headers_after = 25
+ t.header_separator = True
+ t.print_table()
+ print '# of rotations: %d' % (n + 1)
if __name__ == '__main__':
main()
|
rbonvall/grasp-crew-scheduling
|
7a906eca7e71a61ffd2c2a329797540768063080
|
Class for Crew Scheduling instance from ORLIB
|
diff --git a/csp.py b/csp.py
new file mode 100644
index 0000000..3d29ea1
--- /dev/null
+++ b/csp.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python
+
+from collections import defaultdict
+
+class CrewSchedulingProblem:
+ """Crew Scheduling problem instance from ORLIB."""
+ def __init__(self, input_file):
+ file_contents = [tuple(map(int, line.split())) for line in input_file]
+ nr_tasks, time_limit = file_contents.pop(0)
+
+ self.time_limit = time_limit
+ self.tasks = file_contents[:nr_tasks]
+ self.transition_costs = defaultdict(lambda: float('inf'))
+ self.possible_transitions = [list() for task in self.tasks]
+ for i, j, cost in file_contents[nr_tasks:]:
+ # Reindex to start from 0, not from 1 as in ORLIB instances
+ self.transition_costs[i - 1, j - 1] = cost
+ self.possible_transitions[i - 1].append(j - 1)
+
+
+def main():
+ import sys
+
+ if len(sys.argv) < 2 or sys.argv[1] == '-':
+ problem_file = sys.stdin
+ else:
+ try:
+ problem_file = open(sys.argv[1])
+ except IOError:
+ sys.stderr.write("Couldn't open file %s\n" % problem_file)
+ sys.exit(-1)
+
+ csp = CrewSchedulingProblem(problem_file)
+
+ if problem_file == sys.stdin:
+ print '--- Problem from stdin ---'
+ else:
+ print '--- Problem: %s ---' % (sys.argv[1])
+
+ print 'Problem size: %d' % len(csp.tasks)
+ print 'Time limit: %d ' % csp.time_limit
+ print 'Transitions: %d ' % len(csp.transition_costs)
+
+
+if __name__ == '__main__':
+ main()
+
|
wjwwood/Auburn-Lunar-Excavator
|
6e9e0348d6c49720f7e2f46d110910ca54c58ba0
|
Added vlc source files.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0d20b64
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+*.pyc
diff --git a/controlcenter.py b/controlcenter.py
index f700e60..8a825d2 100755
--- a/controlcenter.py
+++ b/controlcenter.py
@@ -1,552 +1,552 @@
#!/usr/bin/env python
# encoding: utf-8
"""
controlcenter.py
Created by William Woodall on 2010-04-22.
"""
__author__ = "William Woodall"
__copyright__ = "Copyright (c) 2009 William Woodall"
### Imports ###
# Standard Python Libraries
import sys
import os
import telnetlib
import time
from socket import *
from logerror import logError
try: # try to catch any missing dependancies
# <PKG> for <PURPOSE>
PKGNAME = 'pygame'
import pygame
from pygame.locals import *
PKGNAME= 'Simple PyGame GUI'
sys.path.append('vendor')
import gui
from gui import *
PKGNAME = 'pyserial'
import serial
from serial import Serial
del PKGNAME
except ImportError as e: # We are missing something, let them know...
- sys.stderr.write("You might not have the "+PKGNAME+" module, try 'easy_install "+PKGNAME+"', else consult google.\n"+str(e))
+ sys.stderr.write("You might not have the "+PKGNAME+" module, try 'easy_install "+PKGNAME+"', else consult google.\n"+str(e)+"\n")
sys.exit(-1)
### Static Variables ###
# Joystick Defaults (Don't change here change in Joystick Control)
DEAD_MAN_BUTTON = 4
SPEED_AXIS = 1
INVERT_SPEED = True
SPEED_SCALAR = 1.11
DIRECTION_AXIS = 0
INVERT_DIRECTION = True
DIRECTION_SCALAR = 1.11
SPEED_AND_DIRECTION_SENSITIVITY = .05
SPEED_AND_DIRECTION_DEAD_ZONE = .25
LIFT_AND_BUCKET_AXIS = 3
LIFT_AND_BUCKET_SCALAR = 1.33
LIFT_AND_BUCKET_TOGGLE_BUTTON = 5
IF_BUCKET = 1
INVERT_LIFT = False
LIFT_SENSITIVITY = .1
LIFT_DEAD_ZONE = .25
INVERT_BUCKET = False
BUCKET_SENSITIVITY = .1
BUCKET_DEAD_ZONE = .25
# Serial
DEFAULT_SERIAL_PORT = "COM9"
# GUI
X = 1280
Y = 800
X_BUFFER = 30
Y_BUFFER = 30
### Classes ###
class joystick_handler(object):
"""Joystick proxy, Taken and modified from: http://bitbucket.org/denilsonsa/pygame-joystick-test"""
def __init__(self, joy_id):
self.id = joy_id
self.joy = pygame.joystick.Joystick(joy_id)
self.name = self.joy.get_name()
self.joy.init()
self.numaxes = self.joy.get_numaxes()
self.numballs = self.joy.get_numballs()
self.numbuttons = self.joy.get_numbuttons()
self.numhats = self.joy.get_numhats()
self.axis = []
for i in xrange(self.numaxes):
self.axis.append(self.joy.get_axis(i))
self.ball = []
for i in xrange(self.numballs):
self.ball.append(self.joy.get_ball(i))
self.button = []
for i in xrange(self.numbuttons):
self.button.append(self.joy.get_button(i))
self.hat = []
for i in xrange(self.numhats):
self.hat.append(self.joy.get_hat(i))
def __repr__(self):
result = ""
result += "Joystick %s\n" % self.name
if self.numaxes > 0:
result += "Axes:\n"
for axis in xrange(self.numaxes):
result += "Axis %d: %1.10f\n" % (axis, self.axis[axis])
if result[-1] != "\n": result += "\n"
if self.numballs > 0:
result += "Balls:\n"
for ball in xrange(self.numballs):
result += "Ball %d: %1.10f " % (ball, self.ball[ball])
if ball % 2 == 1:
result += "\n"
if result[-1] != "\n": result += "\n"
if self.numbuttons > 0:
result += "Buttons:\n"
for button in xrange(self.numbuttons):
result += "Button %2d: %d" % (button, self.button[button])
if (button+1) % 6 == 0:
result += "\n"
elif button != self.numbuttons-1:
result += " | "
if result[-1] != "\n": result += "\n"
if self.numhats > 0:
result += "Hats:\n"
for hat in xrange(self.numhats):
result += "Hat "+str(hat)+": "+str(self.hat[hat])+"\n"
if result[-1] != "\n": result += "\n"
return result
def quit(self):
"""uninit the joystick"""
if self.joy.get_init():
self.joy.quit()
class Excavator(object):
"""Proxy for the Arduino controlling the excavator"""
def __init__(self, desktop, comm_port=None, comm_type="Telnet"):
self.comm_port = comm_port
self.comm_type = comm_type
self.desktop = desktop
self.debug_window = Label(position = (300,210),size = (200,100), parent = self.desktop, text = "Excavator Output:")
self.speed = 0
self.direction = 0
self.lift = 0
self.bucket = 0
def updateDisplay(self):
"""Updates the debug display"""
output = "Excavator Output:\n"
output += "Speed: "+str(self.speed)+"\n"
output += "Direction: "+str(self.direction)+"\n"
output += "Left Motor: "+str(self.left)+"\n"
output += "Right Motor: "+str(self.right)+"\n"
output += "Lift Speed: "+str(self.lift)+"\n"
output += "Bucket Speed: "+str(self.bucket)+"\n"
self.debug_window.text = output
def move(self):
"""Sends the current speed as a command to the excavator"""
bucket_speed = self.speed
leftSpeed = self.speed
rightSpeed = self.speed
#Account for direction
leftSpeed = leftSpeed + self.direction
rightSpeed = rightSpeed - self.direction
#Account for going over 1.0 or under -1.0
if leftSpeed < -1.0:
leftSpeed = -1.0
if leftSpeed > 1.0:
leftSpeed = 1.0
if rightSpeed < -1.0:
rightSpeed = -1.0
if rightSpeed > 1.0:
rightSpeed = 1.0
#Send the commands
leftSpeed *= 64
rightSpeed *= 64
self.left = leftSpeed
self.right = rightSpeed
try:
if self.comm_port:
self.comm_port.write(" m 2 "+str(int(leftSpeed))+"\r")
self.comm_port.write(" m 1 "+str(int(rightSpeed))+"\r")
except:
logError(sys.exc_info(), self.desktop.logerr, "Exception when sending commands to Excavator, if the comm_port \nisn't connected maybe a powerloss on the lantrix board occured: ")
def sendLift(self):
"""Sends the current lift as a command to the excavator"""
lift_speed = self.lift
if lift_speed < -1.0:
lift_speed = -1.0
if lift_speed > 1.0:
lift_speed = 1.0
lift_speed *= 64
try:
if self.comm_port:
self.comm_port.write(" a 1 "+str(int(lift_speed))+"\r")
except:
logError(sys.exc_info(), self.desktop.logerr, "Exception when sending commands to Excavator, if the comm_port \nisn't connected maybe a powerloss on the lantrix board occured: ")
def sendBucket(self):
"""Sends the current bucket as a command to the excavator"""
bucket_speed = self.bucket
if bucket_speed < -1.0:
bucket_speed = -1.0
if bucket_speed > 1.0:
bucket_speed = 1.0
bucket_speed *= 64
try:
if self.comm_port:
self.comm_port.write(" a 2 "+str(int(bucket_speed))+"\r")
except:
logError(sys.exc_info(), self.desktop.logerr, "Exception when sending commands to Excavator, if the comm_port \nisn't connected maybe a powerloss on the lantrix board occured: ")
def update(self, joystick):
"""Updates the excavator, if necessary, given a joystick_handler"""
try:
if not self.comm_port or not joystick:
self.debug_window.text = "Excavator Output:\nNot Processing Currently."
return
speed_needs_to_be_updated = False
direction_needs_to_be_updated = False
lift_needs_to_be_updated = False
bucket_needs_to_be_updated = False
# The dead man button is pressed do speed and direction
if joystick.button[DEAD_MAN_BUTTON] == 1:
# Check if the speed needs to be updated
temp_speed = joystick.axis[SPEED_AXIS]
if INVERT_SPEED:
temp_speed *= -1
if abs(temp_speed) < SPEED_AND_DIRECTION_DEAD_ZONE:
self.speed = 0
speed_needs_to_be_updated = True
elif abs(self.speed - temp_speed) >= SPEED_AND_DIRECTION_SENSITIVITY:
self.speed = temp_speed*SPEED_SCALAR
speed_needs_to_be_updated = True
# Check if the speed needs to be updated
temp_direction = joystick.axis[DIRECTION_AXIS]
if INVERT_DIRECTION:
temp_direction *= -1
if abs(temp_direction) < SPEED_AND_DIRECTION_DEAD_ZONE:
self.direction = 0
direction_needs_to_be_updated = True
elif abs(self.direction - temp_direction) >= SPEED_AND_DIRECTION_SENSITIVITY:
self.direction = temp_direction*DIRECTION_SCALAR
direction_needs_to_be_updated = True
else: # Dead man switch off, stop the motors
self.speed = 0
speed_needs_to_be_updated = True
self.direction = 0
direction_needs_to_be_updated = True
# Check if the lift/bucket needs to be updated
if joystick.button[LIFT_AND_BUCKET_TOGGLE_BUTTON] == IF_BUCKET: # If the bucket
self.lift = 0
lift_needs_to_be_updated = True
temp_bucket = joystick.axis[LIFT_AND_BUCKET_AXIS]
if INVERT_BUCKET:
temp_bucket *= -1
if abs(temp_bucket) < BUCKET_DEAD_ZONE:
self.bucket = 0
bucket_needs_to_be_updated = True
elif abs(self.bucket - temp_bucket) >= BUCKET_SENSITIVITY:
self.bucket = temp_bucket*LIFT_AND_BUCKET_SCALAR
bucket_needs_to_be_updated = True
else: # If the Lift
self.bucket = 0
bucket_needs_to_be_updated = True
temp_lift = joystick.axis[LIFT_AND_BUCKET_AXIS]
if INVERT_LIFT:
temp_lift *= -1
if abs(temp_lift) < LIFT_DEAD_ZONE:
self.lift = 0
lift_needs_to_be_updated = True
if abs(self.lift - temp_lift) >= LIFT_SENSITIVITY:
self.lift = temp_lift*LIFT_AND_BUCKET_SCALAR
lift_needs_to_be_updated = True
# Send new commands if necessary
if speed_needs_to_be_updated or direction_needs_to_be_updated:
self.move()
if lift_needs_to_be_updated:
self.sendLift()
if bucket_needs_to_be_updated:
self.sendBucket()
# Update the display
self.updateDisplay()
except:
logError(sys.exc_info(), self.desktop.logerr, "Exception reading joystick data @ %s: " % str(time.time()))
class TestingCommPort(object):
"""Stub comm port for testing, logs out going data to a file"""
def __init__(self):
self.log_file = open("testing_output.txt", "w+")
def read(self, bytes = 0):
"""Reads"""
pass
def write(self, message):
"""Writes the message to a logging file"""
self.log_file.write(message)
class ControlCenterDesktop(Desktop):
"""The main control center window"""
def __init__(self):
Desktop.__init__(self)
self.running = True
self.comm_mode = "Telnet"
self.layoutDesktop()
# Setup exit button
exit_button_image = pygame.image.load('vendor/art/exit.png').convert()
exit_button_style = createImageButtonStyle(exit_button_image, 15)
self.exit_button = ImageButton((X-20,10), self, exit_button_style)
self.exit_button.onClick = self.close
# Initialize the Error display
self.error_display = ErrorDisplay(self)
self.logerr = self.error_display.logerr
# Initialize the FPS Display
self.fps_display = FPSDisplay(self)
self.fps_label = self.fps_display.fps_label
# Initialize telnet_serial_selector
self.telnet_serial_selector = TelnetSerialSelector(self)
# Setup the Serial Controls
self.serial_controls = SerialControls(self)
self.serial_controls.hide()
# Setup the Telnet Controls
self.telnet_controls = TelnetControls(self)
# Setup the Testing Controls
self.testing_controls = TestingControls(self)
# Setup Joystick Control
self.joystick_controls = JoystickControl(self)
self.joy = self.joystick_controls.joystick
# Setup Excavator Proxy
self.excavator = Excavator(self)
def close(self, button=None):
"""Called when the program needs to exit"""
if self.comm_mode == "Telnet":
self.telnet_controls.disconnect(None)
elif self.comm_mode == "Serial":
self.serial_controls.disconnect(None)
else:
self.testing_controls.disconnect(None)
self.running = False
def switchToTelnet(self):
"""Performs necessary actions to switch to telnet communication mode"""
self.comm_mode = "Telnet"
self.serial_controls.hide()
self.telnet_controls.show()
self.testing_controls.hide()
def switchToSerial(self):
"""Performs necessary actions to switch to serial communication mode"""
self.comm_mode = "Serial"
self.telnet_controls.hide()
self.serial_controls.show()
self.testing_controls.hide()
def switchToTesting(self):
"""Performs necessary actions to switch to Testing Mode"""
self.comm_mode = "Serial"
self.telnet_controls.hide()
self.serial_controls.hide()
self.testing_controls.show()
def connected(self):
"""Called when we are connected to the Excavator"""
if self.comm_mode == "Telnet":
self.excavator.comm_mode = "Telnet"
self.excavator.comm_port = self.telnet_controls.telnet
self.telnet_controls.remote_start_button.enabled = True
elif self.comm_mode == "Serial":
self.excavator.comm_mode = "Serial"
self.excavator.comm_port = self.serial_controls.serial
elif self.comm_mode == "Testing":
self.excavator.comm_mode = "Testing"
self.excavator.comm_port = TestingCommPort()
self.joystick_controls.enable()
def disconnected(self):
"""Called when we are disconnected from the Excavator"""
if self.comm_mode == "Telnet":
self.telnet_controls.sendRemoteStop()
self.telnet_controls.remote_start_button.enabled = False
self.joystick_controls.disable()
def layoutDesktop(self):
"""Initial setup for the desktop"""
# Setup background image
self.bg_image = pygame.image.load('vendor/art/back.png').convert()
# Set the Title bar text
display.set_caption('Auburn Lunar Excavator Control Center')
def update(self):
"""Overrides the builtin update"""
self.joystick_controls.update()
Desktop.update(self)
class TelnetControls(object):
"""Contains elements related to connecting and controlling via telnet"""
def __init__(self, desktop):
self.desktop = desktop
y_offset = 55
self.telnet = None
# Connect button
self.connect_button = Button(position = (X_BUFFER, y_offset), size = (100,0), parent = desktop, text = "Connect")
self.connect_button.onClick = self.connect
# Telnet IP text box
self.telnet_ip = TextBox(position = (X_BUFFER+110, y_offset), size = (200, 0), parent = desktop, text = "192.168.1.5:5000")
# Remote Start button
self.remote_start_button = Button(position = (X_BUFFER, y_offset+25), size = (100,0), parent = desktop, text = "Remote Start")
self.remote_start_button.onClick = self.sendRemoteStart
self.remote_start_button.enabled = False
def sendRemoteStart(self, button=None):
"""Sends the remote start command to the excavator"""
# Send magic packet
try:
udp_socket = socket(AF_INET, SOCK_DGRAM)
msg = '\x1B'+'\x01\x00\x00\x00'+'\x01\x00\x00\x00'
host, _ = self.telnet_ip.text.split(':')
udp_socket.sendto(msg, (host,0x77f0))
udp_socket.close()
except:
logError(sys.exc_info(), self.desktop.logerr, "Exception Sending Start Command: ")
# Reconfigure button
self.remote_start_button.text = "Remote Stop"
self.remote_start_button.onClick = self.sendRemoteStop
def sendRemoteStop(self, button=None):
"""Sends the remote stop command to the excavator"""
# Send magic packet
try:
udp_socket = socket(AF_INET, SOCK_DGRAM)
msg = '\x1B'+'\x01\x00\x00\x00'+'\x00\x00\x00\x00'
host, _ = self.telnet_ip.text.split(':')
udp_socket.sendto(msg, (host,0x77f0))
udp_socket.close()
except:
logError(sys.exc_info(), self.desktop.logerr, "Exception Sending Stop Command: ")
# Reconfigure button
self.remote_start_button.text = "Remote Start"
self.remote_start_button.onClick = self.sendRemoteStart
def connect(self, button):
"""Called when connect is clicked"""
# Try to connect
try:
host, port = self.telnet_ip.text.split(":")
self.telnet = telnetlib.Telnet(host, int(port), 30)
except:
logError(sys.exc_info(), self.desktop.logerr, "Exception connecting via Telnet, %s:%s: " % (type(host), type(port)))
# Disable the connector
self.desktop.telnet_serial_selector.disable()
# Change the connect button to disconnect
self.connect_button.text = "Disconnect"
self.connect_button.onClick = self.disconnect
# Nofity the desktop
self.desktop.connected()
def disconnect(self, button):
"""Called when disconnect clicked"""
self.sendRemoteStop()
# Disconnect from telnet
if self.telnet:
self.telnet.close()
self.telnet = None
# Enable the connectors
self.desktop.telnet_serial_selector.enable()
# Change the disconnect button to connect
self.connect_button.text = "Connect"
self.connect_button.onClick = self.connect
# Nofity the desktop
self.desktop.disconnected()
def hide(self):
"""Hides all the elements"""
self.connect_button.visible = False
self.telnet_ip.visible = False
self.remote_start_button.visible = False
def show(self):
"""Shows all the elements"""
self.connect_button.visible = True
self.telnet_ip.visible = True
self.remote_start_button.visible = True
class TestingControls(object):
"""Contains elements related to connecting and controlling using test mode"""
def __init__(self, desktop):
self.desktop = desktop
y_offset = 55
# Connect button
self.connect_button = Button(position = (X_BUFFER, y_offset), size = (100,0), parent = desktop, text = "Connect")
self.connect_button.onClick = self.connect
def connect(self, button):
"""Called when connect is clicked"""
# Disable the connector
self.desktop.telnet_serial_selector.disable()
# Change the connect button to disconnect
self.connect_button.text = "Disconnect"
self.connect_button.onClick = self.disconnect
# Nofity the desktop
self.desktop.connected()
def disconnect(self, button):
"""Called when disconnect clicked"""
# Enable the connectors
self.desktop.telnet_serial_selector.enable()
# Change the disconnect button to connect
self.connect_button.text = "Connect"
self.connect_button.onClick = self.connect
# Nofity the desktop
self.desktop.disconnected()
diff --git a/vlc.py b/vlc.py
new file mode 100644
index 0000000..075a2d1
--- /dev/null
+++ b/vlc.py
@@ -0,0 +1,5286 @@
+#! /usr/bin/python
+
+#
+# Python ctypes bindings for VLC
+# Copyright (C) 2009 the VideoLAN team
+# $Id: $
+#
+# Authors: Olivier Aubert <olivier.aubert at liris.cnrs.fr>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
+#
+
+"""This module provides bindings for the
+U{libvlc<http://wiki.videolan.org/ExternalAPI>}.
+
+You can find documentation at U{http://www.advene.org/download/python-ctypes/}.
+
+Basically, the most important class is L{Instance}, which is used to
+create a libvlc Instance. From this instance, you can then create
+L{MediaPlayer} and L{MediaListPlayer} instances.
+"""
+
+import ctypes
+import sys
+import os
+
+build_date="Thu Nov 18 18:34:30 2010"
+
+# Used for win32 and MacOS X
+detected_plugin_path=None
+
+if sys.platform.startswith('linux'):
+ try:
+ dll=ctypes.CDLL('libvlc.so')
+ except OSError:
+ dll=ctypes.CDLL('libvlc.so.5')
+
+elif sys.platform.startswith('win'):
+ import ctypes.util
+ p=ctypes.util.find_library('libvlc.dll')
+ current_path = os.getcwd()
+ if p is None:
+ import _winreg # Try to use registry settings
+ for r in _winreg.HKEY_LOCAL_MACHINE, _winreg.HKEY_CURRENT_USER:
+ try:
+ r = _winreg.OpenKey(r, 'Software\\VideoLAN\\VLC')
+ detected_plugin_path, _ = _winreg.QueryValueEx(r, 'InstallDir')
+ _winreg.CloseKey(r)
+ break
+ except _winreg.error:
+ pass
+ else: # Try some standard locations.
+ for p in ('c:\\Program Files', 'c:'):
+ p += '\\VideoLAN\\VLC\\libvlc.dll'
+ if os.path.exists(p):
+ detected_plugin_path = os.path.dirname(p)
+ break
+ del r, _winreg
+ os.chdir(detected_plugin_path or os.curdir)
+ # If chdir failed, this will not work and raise an exception
+ p = 'libvlc.dll'
+ else:
+ detected_plugin_path = os.path.dirname(p)
+ dll=ctypes.CDLL(p)
+ # Restore correct path once the DLL is loaded
+ os.chdir(current_path)
+ del p
+elif sys.platform.startswith('darwin'):
+ # FIXME: should find a means to configure path
+ d='/Applications/VLC.app/Contents/MacOS'
+ if os.path.exists(d):
+ dll = ctypes.CDLL(d+'/lib/libvlc.dylib')
+ detected_plugin_path = d + '/modules'
+ else: # Hope some default path is set...
+ dll = ctypes.CDLL('libvlc.dylib')
+ del d
+else:
+ raise NotImplementedError('O/S %r not supported' % sys.platform)
+
+#
+# Generated enum types.
+#
+
+
+class _Enum(ctypes.c_ulong):
+ '''Base class
+ '''
+ _names={}
+
+ def __str__(self):
+ n=self._names.get(self.value, '') or ('FIXME_(%r)' % (self.value,))
+ return '.'.join((self.__class__.__name__, n))
+
+ def __repr__(self):
+ return '.'.join((self.__class__.__module__, self.__str__()))
+
+ def __eq__(self, other):
+ return ( (isinstance(other, _Enum) and self.value == other.value)
+ or (isinstance(other, (int, long)) and self.value == other) )
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+class EventType(_Enum):
+ """Event types.
+ """
+ _names={
+ 0: 'MediaMetaChanged',
+ 1: 'MediaSubItemAdded',
+ 2: 'MediaDurationChanged',
+ 3: 'MediaParsedChanged',
+ 4: 'MediaFreed',
+ 5: 'MediaStateChanged',
+ 0x100: 'MediaPlayerMediaChanged',
+ 257: 'MediaPlayerNothingSpecial',
+ 258: 'MediaPlayerOpening',
+ 259: 'MediaPlayerBuffering',
+ 260: 'MediaPlayerPlaying',
+ 261: 'MediaPlayerPaused',
+ 262: 'MediaPlayerStopped',
+ 263: 'MediaPlayerForward',
+ 264: 'MediaPlayerBackward',
+ 265: 'MediaPlayerEndReached',
+ 266: 'MediaPlayerEncounteredError',
+ 267: 'MediaPlayerTimeChanged',
+ 268: 'MediaPlayerPositionChanged',
+ 269: 'MediaPlayerSeekableChanged',
+ 270: 'MediaPlayerPausableChanged',
+ 271: 'MediaPlayerTitleChanged',
+ 272: 'MediaPlayerSnapshotTaken',
+ 273: 'MediaPlayerLengthChanged',
+ 0x200: 'MediaListItemAdded',
+ 513: 'MediaListWillAddItem',
+ 514: 'MediaListItemDeleted',
+ 515: 'MediaListWillDeleteItem',
+ 0x300: 'MediaListViewItemAdded',
+ 769: 'MediaListViewWillAddItem',
+ 770: 'MediaListViewItemDeleted',
+ 771: 'MediaListViewWillDeleteItem',
+ 0x400: 'MediaListPlayerPlayed',
+ 1025: 'MediaListPlayerNextItemSet',
+ 1026: 'MediaListPlayerStopped',
+ 0x500: 'MediaDiscovererStarted',
+ 1281: 'MediaDiscovererEnded',
+ 0x600: 'VlmMediaAdded',
+ 1537: 'VlmMediaRemoved',
+ 1538: 'VlmMediaChanged',
+ 1539: 'VlmMediaInstanceStarted',
+ 1540: 'VlmMediaInstanceStopped',
+ 1541: 'VlmMediaInstanceStatusInit',
+ 1542: 'VlmMediaInstanceStatusOpening',
+ 1543: 'VlmMediaInstanceStatusPlaying',
+ 1544: 'VlmMediaInstanceStatusPause',
+ 1545: 'VlmMediaInstanceStatusEnd',
+ 1546: 'VlmMediaInstanceStatusError',
+ }
+EventType.MediaDiscovererEnded=EventType(1281)
+EventType.MediaDiscovererStarted=EventType(0x500)
+EventType.MediaDurationChanged=EventType(2)
+EventType.MediaFreed=EventType(4)
+EventType.MediaListItemAdded=EventType(0x200)
+EventType.MediaListItemDeleted=EventType(514)
+EventType.MediaListPlayerNextItemSet=EventType(1025)
+EventType.MediaListPlayerPlayed=EventType(0x400)
+EventType.MediaListPlayerStopped=EventType(1026)
+EventType.MediaListViewItemAdded=EventType(0x300)
+EventType.MediaListViewItemDeleted=EventType(770)
+EventType.MediaListViewWillAddItem=EventType(769)
+EventType.MediaListViewWillDeleteItem=EventType(771)
+EventType.MediaListWillAddItem=EventType(513)
+EventType.MediaListWillDeleteItem=EventType(515)
+EventType.MediaMetaChanged=EventType(0)
+EventType.MediaParsedChanged=EventType(3)
+EventType.MediaPlayerBackward=EventType(264)
+EventType.MediaPlayerBuffering=EventType(259)
+EventType.MediaPlayerEncounteredError=EventType(266)
+EventType.MediaPlayerEndReached=EventType(265)
+EventType.MediaPlayerForward=EventType(263)
+EventType.MediaPlayerLengthChanged=EventType(273)
+EventType.MediaPlayerMediaChanged=EventType(0x100)
+EventType.MediaPlayerNothingSpecial=EventType(257)
+EventType.MediaPlayerOpening=EventType(258)
+EventType.MediaPlayerPausableChanged=EventType(270)
+EventType.MediaPlayerPaused=EventType(261)
+EventType.MediaPlayerPlaying=EventType(260)
+EventType.MediaPlayerPositionChanged=EventType(268)
+EventType.MediaPlayerSeekableChanged=EventType(269)
+EventType.MediaPlayerSnapshotTaken=EventType(272)
+EventType.MediaPlayerStopped=EventType(262)
+EventType.MediaPlayerTimeChanged=EventType(267)
+EventType.MediaPlayerTitleChanged=EventType(271)
+EventType.MediaStateChanged=EventType(5)
+EventType.MediaSubItemAdded=EventType(1)
+EventType.VlmMediaAdded=EventType(0x600)
+EventType.VlmMediaChanged=EventType(1538)
+EventType.VlmMediaInstanceStarted=EventType(1539)
+EventType.VlmMediaInstanceStatusEnd=EventType(1545)
+EventType.VlmMediaInstanceStatusError=EventType(1546)
+EventType.VlmMediaInstanceStatusInit=EventType(1541)
+EventType.VlmMediaInstanceStatusOpening=EventType(1542)
+EventType.VlmMediaInstanceStatusPause=EventType(1544)
+EventType.VlmMediaInstanceStatusPlaying=EventType(1543)
+EventType.VlmMediaInstanceStopped=EventType(1540)
+EventType.VlmMediaRemoved=EventType(1537)
+
+class Meta(_Enum):
+ """Meta data types */.
+ """
+ _names={
+ 0: 'Title',
+ 1: 'Artist',
+ 2: 'Genre',
+ 3: 'Copyright',
+ 4: 'Album',
+ 5: 'TrackNumber',
+ 6: 'Description',
+ 7: 'Rating',
+ 8: 'Date',
+ 9: 'Setting',
+ 10: 'URL',
+ 11: 'Language',
+ 12: 'NowPlaying',
+ 13: 'Publisher',
+ 14: 'EncodedBy',
+ 15: 'ArtworkURL',
+ 16: 'TrackID',
+ }
+Meta.Album=Meta(4)
+Meta.Artist=Meta(1)
+Meta.ArtworkURL=Meta(15)
+Meta.Copyright=Meta(3)
+Meta.Date=Meta(8)
+Meta.Description=Meta(6)
+Meta.EncodedBy=Meta(14)
+Meta.Genre=Meta(2)
+Meta.Language=Meta(11)
+Meta.NowPlaying=Meta(12)
+Meta.Publisher=Meta(13)
+Meta.Rating=Meta(7)
+Meta.Setting=Meta(9)
+Meta.Title=Meta(0)
+Meta.TrackID=Meta(16)
+Meta.TrackNumber=Meta(5)
+Meta.URL=Meta(10)
+
+class State(_Enum):
+ """Note the order of libvlc_state_t enum must match exactly the order of
+\see mediacontrol_playerstatus, \see input_state_e enums,
+and videolan.libvlc.state (at bindings/cil/src/media.cs).
+expected states by web plugins are:
+idle/close=0, opening=1, buffering=2, playing=3, paused=4,
+stopping=5, ended=6, error=7.
+ """
+ _names={
+ 0: 'NothingSpecial',
+ 1: 'Opening',
+ 2: 'Buffering',
+ 3: 'Playing',
+ 4: 'Paused',
+ 5: 'Stopped',
+ 6: 'Ended',
+ 7: 'Error',
+ }
+State.Buffering=State(2)
+State.Ended=State(6)
+State.Error=State(7)
+State.NothingSpecial=State(0)
+State.Opening=State(1)
+State.Paused=State(4)
+State.Playing=State(3)
+State.Stopped=State(5)
+
+class TrackType(_Enum):
+ """
+ """
+ _names={
+ -1: 'unknown',
+ 0: 'audio',
+ 1: 'video',
+ 2: 'text',
+ }
+TrackType.audio=TrackType(0)
+TrackType.text=TrackType(2)
+TrackType.unknown=TrackType(-1)
+TrackType.video=TrackType(1)
+
+class PlaybackMode(_Enum):
+ """Defines playback modes for playlist.
+ """
+ _names={
+ 0: 'default',
+ 1: 'loop',
+ 2: 'repeat',
+ }
+PlaybackMode.default=PlaybackMode(0)
+PlaybackMode.loop=PlaybackMode(1)
+PlaybackMode.repeat=PlaybackMode(2)
+
+class VideoMarqueeOption(_Enum):
+ """Marq options definition.
+ """
+ _names={
+ 0: 'Enable',
+ 1: 'Text',
+ 2: 'Color',
+ 3: 'Opacity',
+ 4: 'Position',
+ 5: 'Refresh',
+ 6: 'Size',
+ 7: 'Timeout',
+ 8: 'marquee_X',
+ 9: 'marquee_Y',
+ }
+VideoMarqueeOption.Color=VideoMarqueeOption(2)
+VideoMarqueeOption.Enable=VideoMarqueeOption(0)
+VideoMarqueeOption.Opacity=VideoMarqueeOption(3)
+VideoMarqueeOption.Position=VideoMarqueeOption(4)
+VideoMarqueeOption.Refresh=VideoMarqueeOption(5)
+VideoMarqueeOption.Size=VideoMarqueeOption(6)
+VideoMarqueeOption.Text=VideoMarqueeOption(1)
+VideoMarqueeOption.Timeout=VideoMarqueeOption(7)
+VideoMarqueeOption.marquee_X=VideoMarqueeOption(8)
+VideoMarqueeOption.marquee_Y=VideoMarqueeOption(9)
+
+class NavigateMode(_Enum):
+ """Navigation mode.
+ """
+ _names={
+ 0: 'activate',
+ 1: 'up',
+ 2: 'down',
+ 3: 'left',
+ 4: 'right',
+ }
+NavigateMode.activate=NavigateMode(0)
+NavigateMode.down=NavigateMode(2)
+NavigateMode.left=NavigateMode(3)
+NavigateMode.right=NavigateMode(4)
+NavigateMode.up=NavigateMode(1)
+
+class VideoLogoOption(_Enum):
+ """Option values for libvlc_video_{get,set}_logo_{int,string} */.
+ """
+ _names={
+ 0: 'enable',
+ 1: 'file',
+ 2: 'logo_x',
+ 3: 'logo_y',
+ 4: 'delay',
+ 5: 'repeat',
+ 6: 'opacity',
+ 7: 'position',
+ }
+VideoLogoOption.delay=VideoLogoOption(4)
+VideoLogoOption.enable=VideoLogoOption(0)
+VideoLogoOption.file=VideoLogoOption(1)
+VideoLogoOption.logo_x=VideoLogoOption(2)
+VideoLogoOption.logo_y=VideoLogoOption(3)
+VideoLogoOption.opacity=VideoLogoOption(6)
+VideoLogoOption.position=VideoLogoOption(7)
+VideoLogoOption.repeat=VideoLogoOption(5)
+
+class VideoAdjustOption(_Enum):
+ """Option values for libvlc_video_{get,set}_adjust_{int,float,bool} */.
+ """
+ _names={
+ 0: 'Enable',
+ 1: 'Contrast',
+ 2: 'Brightness',
+ 3: 'Hue',
+ 4: 'Saturation',
+ 5: 'Gamma',
+ }
+VideoAdjustOption.Brightness=VideoAdjustOption(2)
+VideoAdjustOption.Contrast=VideoAdjustOption(1)
+VideoAdjustOption.Enable=VideoAdjustOption(0)
+VideoAdjustOption.Gamma=VideoAdjustOption(5)
+VideoAdjustOption.Hue=VideoAdjustOption(3)
+VideoAdjustOption.Saturation=VideoAdjustOption(4)
+
+class AudioOutputDeviceTypes(_Enum):
+ """Audio device types.
+ """
+ _names={
+ -1: 'Error',
+ 1: 'Mono',
+ 2: 'Stereo',
+ 4: '_2F2R',
+ 5: '_3F2R',
+ 6: '_5_1',
+ 7: '_6_1',
+ 8: '_7_1',
+ 10: 'SPDIF',
+ }
+AudioOutputDeviceTypes.Error=AudioOutputDeviceTypes(-1)
+AudioOutputDeviceTypes.Mono=AudioOutputDeviceTypes(1)
+AudioOutputDeviceTypes.SPDIF=AudioOutputDeviceTypes(10)
+AudioOutputDeviceTypes.Stereo=AudioOutputDeviceTypes(2)
+AudioOutputDeviceTypes._2F2R=AudioOutputDeviceTypes(4)
+AudioOutputDeviceTypes._3F2R=AudioOutputDeviceTypes(5)
+AudioOutputDeviceTypes._5_1=AudioOutputDeviceTypes(6)
+AudioOutputDeviceTypes._6_1=AudioOutputDeviceTypes(7)
+AudioOutputDeviceTypes._7_1=AudioOutputDeviceTypes(8)
+
+class AudioOutputChannel(_Enum):
+ """Audio channels.
+ """
+ _names={
+ -1: 'Error',
+ 1: 'Stereo',
+ 2: 'RStereo',
+ 3: 'Left',
+ 4: 'Right',
+ 5: 'Dolbys',
+ }
+AudioOutputChannel.Dolbys=AudioOutputChannel(5)
+AudioOutputChannel.Error=AudioOutputChannel(-1)
+AudioOutputChannel.Left=AudioOutputChannel(3)
+AudioOutputChannel.RStereo=AudioOutputChannel(2)
+AudioOutputChannel.Right=AudioOutputChannel(4)
+AudioOutputChannel.Stereo=AudioOutputChannel(1)
+
+
+#
+# End of generated enum types.
+#
+
+class ListPOINTER(object):
+ '''Just like a POINTER but accept a list of ctype as an argument.
+ '''
+ def __init__(self, etype):
+ self.etype = etype
+
+ def from_param(self, param):
+ if isinstance(param, (list, tuple)):
+ return (self.etype * len(param))(*param)
+
+class LibVLCException(Exception):
+ """Python exception raised by libvlc methods.
+ """
+ pass
+
+# From libvlc_structures.h
+
+class MediaStats(ctypes.Structure):
+ _fields_= [
+ ('read_bytes', ctypes.c_int ),
+ ('input_bitrate', ctypes.c_float),
+ ('demux_read_bytes', ctypes.c_int ),
+ ('demux_bitrate', ctypes.c_float),
+ ('demux_corrupted', ctypes.c_int ),
+ ('demux_discontinuity', ctypes.c_int ),
+ ('decoded_video', ctypes.c_int ),
+ ('decoded_audio', ctypes.c_int ),
+ ('displayed_pictures', ctypes.c_int ),
+ ('lost_pictures', ctypes.c_int ),
+ ('played_abuffers', ctypes.c_int ),
+ ('lost_abuffers', ctypes.c_int ),
+ ('sent_packets', ctypes.c_int ),
+ ('sent_bytes', ctypes.c_int ),
+ ('send_bitrate', ctypes.c_float),
+ ]
+
+ def __str__(self):
+ return "\n".join( [ self.__class__.__name__ ]
+ + [" %s:\t%s" % (n, getattr(self, n)) for n in self._fields_] )
+
+class MediaTrackInfo(ctypes.Structure):
+ _fields_= [
+ ('codec' , ctypes.c_uint32),
+ ('id' , ctypes.c_int),
+ ('type' , TrackType),
+ ('profile' , ctypes.c_int),
+ ('level' , ctypes.c_int),
+ ('channels_or_height', ctypes.c_uint),
+ ('rate_or_width' , ctypes.c_uint),
+ ]
+
+ def __str__(self):
+ return "\n".join( [self.__class__.__name__]
+ + [" %s:\t%s" % (n, getattr(self, n)) for n in self._fields_])
+
+class PlaylistItem(ctypes.Structure):
+ _fields_= [
+ ('id', ctypes.c_int),
+ ('uri', ctypes.c_char_p),
+ ('name', ctypes.c_char_p),
+ ]
+
+ def __str__(self):
+ return "%s #%d %s (uri %s)" % (self.__class__.__name__, self.id, self.name, self.uri)
+
+class LogMessage(ctypes.Structure):
+ _fields_= [
+ ('size', ctypes.c_uint),
+ ('severity', ctypes.c_int),
+ ('type', ctypes.c_char_p),
+ ('name', ctypes.c_char_p),
+ ('header', ctypes.c_char_p),
+ ('message', ctypes.c_char_p),
+ ]
+
+ def __init__(self):
+ super(LogMessage, self).__init__()
+ self.size=ctypes.sizeof(self)
+
+ def __str__(self):
+ return "%s(%d:%s): %s" % (self.__class__.__name__, self.severity, self.type, self.message)
+
+
+class AudioOutput(ctypes.Structure):
+ def __str__(self):
+ return "%s(%s:%s)" % (self.__class__.__name__, self.name, self.description)
+AudioOutput._fields_= [
+ ('name', ctypes.c_char_p),
+ ('description', ctypes.c_char_p),
+ ('next', ctypes.POINTER(AudioOutput)),
+ ]
+
+class TrackDescription(ctypes.Structure):
+ def __str__(self):
+ return "%s(%d:%s)" % (self.__class__.__name__, self.id, self.name)
+TrackDescription._fields_= [
+ ('id', ctypes.c_int),
+ ('name', ctypes.c_char_p),
+ ('next', ctypes.POINTER(TrackDescription)),
+ ]
+def track_description_list(head):
+ """Convert a TrackDescription linked list to a python list, and release the linked list.
+ """
+ l = []
+ if head:
+ item = head
+ while item:
+ l.append( (item.contents.id, item.contents.name) )
+ item = item.contents.next
+ libvlc_track_description_release(head)
+ return l
+
+class MediaEvent(ctypes.Structure):
+ _fields_ = [
+ ('media_name', ctypes.c_char_p),
+ ('instance_name', ctypes.c_char_p),
+ ]
+
+class EventUnion(ctypes.Union):
+ _fields_ = [
+ ('meta_type', ctypes.c_uint),
+ ('new_child', ctypes.c_uint),
+ ('new_duration', ctypes.c_longlong),
+ ('new_status', ctypes.c_int),
+ ('media', ctypes.c_void_p),
+ ('new_state', ctypes.c_uint),
+ # Media instance
+ ('new_position', ctypes.c_float),
+ ('new_time', ctypes.c_longlong),
+ ('new_title', ctypes.c_int),
+ ('new_seekable', ctypes.c_longlong),
+ ('new_pausable', ctypes.c_longlong),
+ # FIXME: Skipped MediaList and MediaListView...
+ ('filename', ctypes.c_char_p),
+ ('new_length', ctypes.c_longlong),
+ ('media_event', MediaEvent),
+ ]
+
+class Event(ctypes.Structure):
+ _fields_ = [
+ ('type', EventType),
+ ('object', ctypes.c_void_p),
+ ('u', EventUnion),
+ ]
+
+class Rectangle(ctypes.Structure):
+ _fields_ = [
+ ('top', ctypes.c_int),
+ ('left', ctypes.c_int),
+ ('bottom', ctypes.c_int),
+ ('right', ctypes.c_int),
+ ]
+
+class Position(object):
+ """Enum-like, position constants for VideoMarqueePosition option.
+ """
+ Center=0
+ Left=1
+ CenterLeft=1
+ Right=2
+ CenterRight=2
+ Top=4
+ TopCenter=4
+ TopLeft=5
+ TopRight=6
+ Bottom=8
+ BottomCenter=8
+ BottomLeft=9
+ BottomRight=10
+
+ def __init__(self):
+ raise TypeError('Constants only')
+
+### End of header.py ###
+class EventManager(object):
+ """Create an event manager and handler.
+
+ This class interposes the registration and handling of
+ event notifications in order to (a) allow any number of
+ positional and/or keyword arguments to the callback (in
+ addition to the Event instance), (b) preserve the Python
+ argument objects and (c) remove the need for decorating
+ each callback with decorator '@callbackmethod'.
+
+ Calls from ctypes to Python callbacks are handled by
+ function _callback_handler.
+
+ A side benefit of this scheme is that the callback and
+ all argument objects remain alive (i.e. are not garbage
+ collected) until *after* the event notification has
+ been unregistered.
+
+ NOTE: only a single notification can be registered for
+ each event type in an EventManager instance.
+ """
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+
+ def __new__(cls, ptr=None):
+ if ptr is None:
+ raise LibVLCException("(INTERNAL) ctypes class.")
+ if ptr == 0:
+ return None
+ o = object.__new__(cls)
+ o._as_parameter_ = ptr # was ctypes.c_void_p(ptr)
+ o._callbacks_ = {} # 3-tuples of Python objs
+ o._callback_handler = None
+ return o
+
+ def event_attach(self, eventtype, callback, *args, **kwds):
+ """Register an event notification.
+
+ @param eventtype: the desired event type to be notified about
+ @param callback: the function to call when the event occurs
+ @param args: optional positional arguments for the callback
+ @param kwds: optional keyword arguments for the callback
+ @return: 0 on success, ENOMEM on error
+
+ NOTE: The callback must have at least one argument, the Event
+ instance. The optional positional and keyword arguments are
+ in addition to the first one.
+ """
+ if not isinstance(eventtype, EventType):
+ raise LibVLCException("%s required: %r" % ('EventType', eventtype))
+ if not hasattr(callback, '__call__'): # callable()
+ raise LibVLCException("%s required: %r" % ('callable', callback))
+
+ if self._callback_handler is None:
+ _called_from_ctypes = ctypes.CFUNCTYPE(None, ctypes.POINTER(Event), ctypes.c_void_p)
+ @_called_from_ctypes
+ def _callback_handler(event, unused):
+ """(INTERNAL) handle callback call from ctypes.
+
+ Note: we cannot simply make this an instance method of
+ EventManager since ctypes callback does not append
+ self as first parameter. Hence we use a closure.
+ """
+ try: # retrieve Python callback and arguments
+ call, args, kwds = self._callbacks_[event.contents.type.value]
+ # We dereference event.contents here to simplify callback code.
+ call(event.contents, *args, **kwds)
+ except KeyError: # detached?
+ pass
+ self._callback_handler = _callback_handler
+
+ r = libvlc_event_attach(self, eventtype, self._callback_handler, None)
+ if not r:
+ self._callbacks_[eventtype.value] = (callback, args, kwds)
+ return r
+
+ def event_detach(self, eventtype):
+ """Unregister an event notification.
+
+ @param eventtype: the event type notification to be removed
+ """
+ if not isinstance(eventtype, EventType):
+ raise LibVLCException("%s required: %r" % ('EventType', eventtype))
+
+ t = eventtype.value
+ if t in self._callbacks_:
+ del self._callbacks_[t] # remove, regardless of libvlc return value
+ libvlc_event_detach(self, eventtype, self._callback_handler, None)
+
+class Instance(object):
+ """Create a new Instance instance.
+
+ It may take as parameter either:
+ - a string
+ - a list of strings as first parameters
+ - the parameters given as the constructor parameters (must be strings)
+ """
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+
+ def __new__(cls, *p):
+ if p and p[0] == 0:
+ return None
+ elif p and isinstance(p[0], (int, long)):
+ # instance creation from ctypes
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(p[0])
+ return o
+ elif len(p) == 1 and isinstance(p[0], basestring):
+ # Only 1 string parameter: should be a parameter line
+ p=p[0].split(' ')
+ elif len(p) == 1 and isinstance(p[0], (tuple, list)):
+ p=p[0]
+
+ if not p and detected_plugin_path is not None:
+ # No parameters passed. Under win32 and MacOS, specify
+ # the detected_plugin_path if present.
+ p=[ 'vlc', '--plugin-path='+ detected_plugin_path ]
+ return libvlc_new(len(p), p)
+
+ def media_player_new(self, uri=None):
+ """Create a new MediaPlayer instance.
+
+ @param uri: an optional URI to play in the player.
+ """
+ p=libvlc_media_player_new(self)
+ if uri:
+ p.set_media(self.media_new(uri))
+ p._instance=self
+ return p
+
+ def media_list_player_new(self):
+ """Create a new MediaListPlayer instance.
+ """
+ p=libvlc_media_list_player_new(self)
+ p._instance=self
+ return p
+
+ def media_new(self, mrl, *options):
+ """Create a new Media instance.
+
+ Options can be specified as supplementary string parameters, e.g.
+ m=i.media_new('foo.avi', 'sub-filter=marq{marquee=Hello}', 'vout-filter=invert')
+ """
+ m=libvlc_media_new_location(self, mrl)
+ for o in options:
+ libvlc_media_add_option(m, o)
+ return m
+
+ def audio_output_enumerate_devices(self):
+ """Enumerate the defined audio output devices.
+
+ The result is a list of dict (name, description)
+ """
+ l = []
+ head = ao = libvlc_audio_output_list_get(self)
+ while ao:
+ l.append( { 'name': ao.contents.name,
+ 'description': ao.contents.description,
+ 'devices': [ { 'id': libvlc_audio_output_device_id(self, ao.contents.name, i),
+ 'longname': libvlc_audio_output_device_longname(self, ao.contents.name, i) }
+ for i in range(libvlc_audio_output_device_count(self, ao.contents.name) ) ] } )
+ ao = ao.contents.next
+ libvlc_audio_output_list_release(head)
+ return l
+
+
+ if hasattr(dll, 'libvlc_release'):
+ def release(self):
+ """Decrement the reference count of a libvlc instance, and destroy it
+if it reaches zero.
+ """
+ return libvlc_release(self)
+
+ if hasattr(dll, 'libvlc_retain'):
+ def retain(self):
+ """Increments the reference count of a libvlc instance.
+The initial reference count is 1 after libvlc_new() returns.
+ """
+ return libvlc_retain(self)
+
+ if hasattr(dll, 'libvlc_add_intf'):
+ def add_intf(self, name):
+ """Try to start a user interface for the libvlc instance.
+@param name: interface name, or NULL for default
+@return: 0 on success, -1 on error.
+ """
+ return libvlc_add_intf(self, name)
+
+ if hasattr(dll, 'libvlc_wait'):
+ def wait(self):
+ """Waits until an interface causes the instance to exit.
+You should start at least one interface first, using libvlc_add_intf().
+ """
+ return libvlc_wait(self)
+
+ if hasattr(dll, 'libvlc_set_user_agent'):
+ def set_user_agent(self, name, http):
+ """Sets the application name. LibVLC passes this as the user agent string
+when a protocol requires it.
+@version: LibVLC 1.1.1 or later
+@param name: human-readable application name, e.g. "FooBar player 1.2.3"
+@param http: HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0"
+ """
+ return libvlc_set_user_agent(self, name, http)
+
+ if hasattr(dll, 'libvlc_get_log_verbosity'):
+ def get_log_verbosity(self):
+ """Return the VLC messaging verbosity level.
+@return: verbosity level for messages
+ """
+ return libvlc_get_log_verbosity(self)
+
+ if hasattr(dll, 'libvlc_set_log_verbosity'):
+ def set_log_verbosity(self, level):
+ """Set the VLC messaging verbosity level.
+@param level: log level
+ """
+ return libvlc_set_log_verbosity(self, level)
+
+ if hasattr(dll, 'libvlc_log_open'):
+ def log_open(self):
+ """Open a VLC message log instance.
+@return: log message instance or NULL on error
+ """
+ return libvlc_log_open(self)
+
+ if hasattr(dll, 'libvlc_media_new_location'):
+ def media_new_location(self, psz_mrl):
+ """Create a media with a certain given media resource location.
+See libvlc_media_release
+@param psz_mrl: the MRL to read
+@return: the newly created media or NULL on error
+ """
+ return libvlc_media_new_location(self, psz_mrl)
+
+ if hasattr(dll, 'libvlc_media_new_path'):
+ def media_new_path(self, path):
+ """Create a media with a certain file path.
+See libvlc_media_release
+@param path: local filesystem path
+@return: the newly created media or NULL on error
+ """
+ return libvlc_media_new_path(self, path)
+
+ if hasattr(dll, 'libvlc_media_new_as_node'):
+ def media_new_as_node(self, psz_name):
+ """Create a media as an empty node with a given name.
+See libvlc_media_release
+@param psz_name: the name of the node
+@return: the new empty media or NULL on error
+ """
+ return libvlc_media_new_as_node(self, psz_name)
+
+ if hasattr(dll, 'libvlc_media_discoverer_new_from_name'):
+ def media_discoverer_new_from_name(self, psz_name):
+ """Discover media service by name.
+@param psz_name: service name
+@return: media discover object or NULL in case of error
+ """
+ return libvlc_media_discoverer_new_from_name(self, psz_name)
+
+ if hasattr(dll, 'libvlc_media_library_new'):
+ def media_library_new(self):
+ """Create an new Media Library object
+@return: a new object or NULL on error
+ """
+ return libvlc_media_library_new(self)
+
+ if hasattr(dll, 'libvlc_media_list_new'):
+ def media_list_new(self):
+ """Create an empty media list.
+@return: empty media list, or NULL on error
+ """
+ return libvlc_media_list_new(self)
+
+ if hasattr(dll, 'libvlc_audio_output_list_get'):
+ def audio_output_list_get(self):
+ """Get the list of available audio outputs
+ In case of error, NULL is returned.
+@return: list of available audio outputs. It must be freed it with
+ """
+ return libvlc_audio_output_list_get(self)
+
+ if hasattr(dll, 'libvlc_audio_output_device_count'):
+ def audio_output_device_count(self, psz_audio_output):
+ """Get count of devices for audio output, these devices are hardware oriented
+like analor or digital output of sound card
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@return: number of devices
+ """
+ return libvlc_audio_output_device_count(self, psz_audio_output)
+
+ if hasattr(dll, 'libvlc_audio_output_device_longname'):
+ def audio_output_device_longname(self, psz_audio_output, i_device):
+ """Get long name of device, if not available short name given
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@param i_device: device index
+@return: long name of device
+ """
+ return libvlc_audio_output_device_longname(self, psz_audio_output, i_device)
+
+ if hasattr(dll, 'libvlc_audio_output_device_id'):
+ def audio_output_device_id(self, psz_audio_output, i_device):
+ """Get id name of device
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@param i_device: device index
+@return: id name of device, use for setting device, need to be free after use
+ """
+ return libvlc_audio_output_device_id(self, psz_audio_output, i_device)
+
+ if hasattr(dll, 'libvlc_vlm_release'):
+ def vlm_release(self):
+ """Release the vlm instance related to the given libvlc_instance_t
+ """
+ return libvlc_vlm_release(self)
+
+ if hasattr(dll, 'libvlc_vlm_add_broadcast'):
+ def vlm_add_broadcast(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop):
+ """Add a broadcast, with one input.
+@param psz_name: the name of the new broadcast
+@param psz_input: the input MRL
+@param psz_output: the output MRL (the parameter to the "sout" variable)
+@param i_options: number of additional options
+@param ppsz_options: additional options
+@param b_enabled: boolean for enabling the new broadcast
+@param b_loop: Should this broadcast be played in loop ?
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_add_broadcast(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop)
+
+ if hasattr(dll, 'libvlc_vlm_add_vod'):
+ def vlm_add_vod(self, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux):
+ """Add a vod, with one input.
+@param psz_name: the name of the new vod media
+@param psz_input: the input MRL
+@param i_options: number of additional options
+@param ppsz_options: additional options
+@param b_enabled: boolean for enabling the new vod
+@param psz_mux: the muxer of the vod media
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_add_vod(self, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux)
+
+ if hasattr(dll, 'libvlc_vlm_del_media'):
+ def vlm_del_media(self, psz_name):
+ """Delete a media (VOD or broadcast).
+@param psz_name: the media to delete
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_del_media(self, psz_name)
+
+ if hasattr(dll, 'libvlc_vlm_set_enabled'):
+ def vlm_set_enabled(self, psz_name, b_enabled):
+ """Enable or disable a media (VOD or broadcast).
+@param psz_name: the media to work on
+@param b_enabled: the new status
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_set_enabled(self, psz_name, b_enabled)
+
+ if hasattr(dll, 'libvlc_vlm_set_output'):
+ def vlm_set_output(self, psz_name, psz_output):
+ """Set the output for a media.
+@param psz_name: the media to work on
+@param psz_output: the output MRL (the parameter to the "sout" variable)
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_set_output(self, psz_name, psz_output)
+
+ if hasattr(dll, 'libvlc_vlm_set_input'):
+ def vlm_set_input(self, psz_name, psz_input):
+ """Set a media's input MRL. This will delete all existing inputs and
+add the specified one.
+@param psz_name: the media to work on
+@param psz_input: the input MRL
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_set_input(self, psz_name, psz_input)
+
+ if hasattr(dll, 'libvlc_vlm_add_input'):
+ def vlm_add_input(self, psz_name, psz_input):
+ """Add a media's input MRL. This will add the specified one.
+@param psz_name: the media to work on
+@param psz_input: the input MRL
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_add_input(self, psz_name, psz_input)
+
+ if hasattr(dll, 'libvlc_vlm_set_loop'):
+ def vlm_set_loop(self, psz_name, b_loop):
+ """Set a media's loop status.
+@param psz_name: the media to work on
+@param b_loop: the new status
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_set_loop(self, psz_name, b_loop)
+
+ if hasattr(dll, 'libvlc_vlm_set_mux'):
+ def vlm_set_mux(self, psz_name, psz_mux):
+ """Set a media's vod muxer.
+@param psz_name: the media to work on
+@param psz_mux: the new muxer
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_set_mux(self, psz_name, psz_mux)
+
+ if hasattr(dll, 'libvlc_vlm_change_media'):
+ def vlm_change_media(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop):
+ """Edit the parameters of a media. This will delete all existing inputs and
+add the specified one.
+@param psz_name: the name of the new broadcast
+@param psz_input: the input MRL
+@param psz_output: the output MRL (the parameter to the "sout" variable)
+@param i_options: number of additional options
+@param ppsz_options: additional options
+@param b_enabled: boolean for enabling the new broadcast
+@param b_loop: Should this broadcast be played in loop ?
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_change_media(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop)
+
+ if hasattr(dll, 'libvlc_vlm_play_media'):
+ def vlm_play_media(self, psz_name):
+ """Play the named broadcast.
+@param psz_name: the name of the broadcast
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_play_media(self, psz_name)
+
+ if hasattr(dll, 'libvlc_vlm_stop_media'):
+ def vlm_stop_media(self, psz_name):
+ """Stop the named broadcast.
+@param psz_name: the name of the broadcast
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_stop_media(self, psz_name)
+
+ if hasattr(dll, 'libvlc_vlm_pause_media'):
+ def vlm_pause_media(self, psz_name):
+ """Pause the named broadcast.
+@param psz_name: the name of the broadcast
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_pause_media(self, psz_name)
+
+ if hasattr(dll, 'libvlc_vlm_seek_media'):
+ def vlm_seek_media(self, psz_name, f_percentage):
+ """Seek in the named broadcast.
+@param psz_name: the name of the broadcast
+@param f_percentage: the percentage to seek to
+@return: 0 on success, -1 on error
+ """
+ return libvlc_vlm_seek_media(self, psz_name, f_percentage)
+
+ if hasattr(dll, 'libvlc_vlm_show_media'):
+ def vlm_show_media(self, psz_name):
+ """Return information about the named media as a JSON
+string representation.
+This function is mainly intended for debugging use,
+if you want programmatic access to the state of
+a vlm_media_instance_t, please use the corresponding
+libvlc_vlm_get_media_instance_xxx -functions.
+Currently there are no such functions available for
+vlm_media_t though.
+ if the name is an empty string, all media is described
+@param psz_name: the name of the media,
+@return: string with information about named media, or NULL on error
+ """
+ return libvlc_vlm_show_media(self, psz_name)
+
+ if hasattr(dll, 'libvlc_vlm_get_media_instance_position'):
+ def vlm_get_media_instance_position(self, psz_name, i_instance):
+ """Get vlm_media instance position by name or instance id
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: position as float or -1. on error
+ """
+ return libvlc_vlm_get_media_instance_position(self, psz_name, i_instance)
+
+ if hasattr(dll, 'libvlc_vlm_get_media_instance_time'):
+ def vlm_get_media_instance_time(self, psz_name, i_instance):
+ """Get vlm_media instance time by name or instance id
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: time as integer or -1 on error
+ """
+ return libvlc_vlm_get_media_instance_time(self, psz_name, i_instance)
+
+ if hasattr(dll, 'libvlc_vlm_get_media_instance_length'):
+ def vlm_get_media_instance_length(self, psz_name, i_instance):
+ """Get vlm_media instance length by name or instance id
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: length of media item or -1 on error
+ """
+ return libvlc_vlm_get_media_instance_length(self, psz_name, i_instance)
+
+ if hasattr(dll, 'libvlc_vlm_get_media_instance_rate'):
+ def vlm_get_media_instance_rate(self, psz_name, i_instance):
+ """Get vlm_media instance playback rate by name or instance id
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: playback rate or -1 on error
+ """
+ return libvlc_vlm_get_media_instance_rate(self, psz_name, i_instance)
+
+ if hasattr(dll, 'libvlc_vlm_get_media_instance_title'):
+ def vlm_get_media_instance_title(self, psz_name, i_instance):
+ """Get vlm_media instance title number by name or instance id
+@bug: will always return 0
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: title as number or -1 on error
+ """
+ return libvlc_vlm_get_media_instance_title(self, psz_name, i_instance)
+
+ if hasattr(dll, 'libvlc_vlm_get_media_instance_chapter'):
+ def vlm_get_media_instance_chapter(self, psz_name, i_instance):
+ """Get vlm_media instance chapter number by name or instance id
+@bug: will always return 0
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: chapter as number or -1 on error
+ """
+ return libvlc_vlm_get_media_instance_chapter(self, psz_name, i_instance)
+
+ if hasattr(dll, 'libvlc_vlm_get_media_instance_seekable'):
+ def vlm_get_media_instance_seekable(self, psz_name, i_instance):
+ """Is libvlc instance seekable ?
+@bug: will always return 0
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: 1 if seekable, 0 if not, -1 if media does not exist
+ """
+ return libvlc_vlm_get_media_instance_seekable(self, psz_name, i_instance)
+
+ if hasattr(dll, 'libvlc_vlm_get_event_manager'):
+ def vlm_get_event_manager(self):
+ """Get libvlc_event_manager from a vlm media.
+The p_event_manager is immutable, so you don't have to hold the lock
+@return: libvlc_event_manager
+ """
+ return libvlc_vlm_get_event_manager(self)
+
+class Log(object):
+ """Create a new VLC log instance.
+ """
+
+ def __new__(cls, pointer=None):
+ '''Internal method used for instanciating wrappers from ctypes.
+ '''
+ if pointer is None:
+ raise Exception("Internal method. Surely this class cannot be instanciated by itself.")
+ if pointer == 0:
+ return None
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(pointer)
+ return o
+
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+
+ def __iter__(self):
+ return self.get_iterator()
+
+ def dump(self):
+ return [ str(m) for m in self ]
+
+
+ if hasattr(dll, 'libvlc_log_close'):
+ def close(self):
+ """Close a VLC message log instance.
+ """
+ return libvlc_log_close(self)
+
+ if hasattr(dll, 'libvlc_log_count'):
+ def count(self):
+ """Returns the number of messages in a log instance.
+@return: number of log messages, 0 if p_log is NULL
+ """
+ return libvlc_log_count(self)
+
+ def __len__(self):
+ return libvlc_log_count(self)
+
+ if hasattr(dll, 'libvlc_log_clear'):
+ def clear(self):
+ """Clear a log instance.
+All messages in the log are removed. The log should be cleared on a
+regular basis to avoid clogging.
+ """
+ return libvlc_log_clear(self)
+
+ if hasattr(dll, 'libvlc_log_get_iterator'):
+ def get_iterator(self):
+ """Allocate and returns a new iterator to messages in log.
+@return: log iterator object or NULL on error
+ """
+ return libvlc_log_get_iterator(self)
+
+class LogIterator(object):
+ """Create a new VLC log iterator.
+ """
+
+ def __new__(cls, pointer=None):
+ '''Internal method used for instanciating wrappers from ctypes.
+ '''
+ if pointer is None:
+ raise Exception("Internal method. Surely this class cannot be instanciated by itself.")
+ if pointer == 0:
+ return None
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(pointer)
+ return o
+
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ if not self.has_next():
+ raise StopIteration
+ buf=LogMessage()
+ ret=libvlc_log_iterator_next(self, buf)
+ return ret.contents
+
+
+ if hasattr(dll, 'libvlc_log_iterator_free'):
+ def free(self):
+ """Release a previoulsy allocated iterator.
+ """
+ return libvlc_log_iterator_free(self)
+
+ if hasattr(dll, 'libvlc_log_iterator_has_next'):
+ def has_next(self):
+ """Return whether log iterator has more messages.
+@return: true if iterator has more message objects, else false
+ """
+ return libvlc_log_iterator_has_next(self)
+
+class Media(object):
+ """Create a new Media instance.
+ """
+
+ def __new__(cls, pointer=None):
+ '''Internal method used for instanciating wrappers from ctypes.
+ '''
+ if pointer is None:
+ raise Exception("Internal method. Surely this class cannot be instanciated by itself.")
+ if pointer == 0:
+ return None
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(pointer)
+ return o
+
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+
+
+ def add_options(self, *list_of_options):
+ """Add a list of options to the media.
+
+ Options must be written without the double-dash, e.g.:
+ m.add_options('sub-filter=marq@test{marquee=Hello}', 'video-filter=invert')
+
+ Note that you also can directly pass these options in the Instance.media_new method:
+ m=instance.media_new( 'foo.avi', 'sub-filter=marq@test{marquee=Hello}', 'video-filter=invert')
+ """
+ for o in list_of_options:
+ self.add_option(o)
+
+
+ if hasattr(dll, 'libvlc_media_add_option'):
+ def add_option(self, ppsz_options):
+ """Add an option to the media.
+This option will be used to determine how the media_player will
+read the media. This allows to use VLC's advanced
+reading/streaming options on a per-media basis.
+The options are detailed in vlc --long-help, for instance "--sout-all"
+@param ppsz_options: the options (as a string)
+ """
+ return libvlc_media_add_option(self, ppsz_options)
+
+ if hasattr(dll, 'libvlc_media_add_option_flag'):
+ def add_option_flag(self, ppsz_options, i_flags):
+ """Add an option to the media with configurable flags.
+This option will be used to determine how the media_player will
+read the media. This allows to use VLC's advanced
+reading/streaming options on a per-media basis.
+The options are detailed in vlc --long-help, for instance "--sout-all"
+@param ppsz_options: the options (as a string)
+@param i_flags: the flags for this option
+ """
+ return libvlc_media_add_option_flag(self, ppsz_options, i_flags)
+
+ if hasattr(dll, 'libvlc_media_retain'):
+ def retain(self):
+ """Retain a reference to a media descriptor object (libvlc_media_t). Use
+libvlc_media_release() to decrement the reference count of a
+media descriptor object.
+ """
+ return libvlc_media_retain(self)
+
+ if hasattr(dll, 'libvlc_media_release'):
+ def release(self):
+ """Decrement the reference count of a media descriptor object. If the
+reference count is 0, then libvlc_media_release() will release the
+media descriptor object. It will send out an libvlc_MediaFreed event
+to all listeners. If the media descriptor object has been released it
+should not be used again.
+ """
+ return libvlc_media_release(self)
+
+ if hasattr(dll, 'libvlc_media_get_mrl'):
+ def get_mrl(self):
+ """Get the media resource locator (mrl) from a media descriptor object
+@return: string with mrl of media descriptor object
+ """
+ return libvlc_media_get_mrl(self)
+
+ if hasattr(dll, 'libvlc_media_duplicate'):
+ def duplicate(self):
+ """Duplicate a media descriptor object.
+ """
+ return libvlc_media_duplicate(self)
+
+ if hasattr(dll, 'libvlc_media_get_meta'):
+ def get_meta(self, e_meta):
+ """Read the meta of the media.
+If the media has not yet been parsed this will return NULL.
+This methods automatically calls libvlc_media_parse_async(), so after calling
+it you may receive a libvlc_MediaMetaChanged event. If you prefer a synchronous
+version ensure that you call libvlc_media_parse() before get_meta().
+See libvlc_media_parse
+See libvlc_media_parse_async
+See libvlc_MediaMetaChanged
+@param e_meta: the meta to read
+@return: the media's meta
+ """
+ return libvlc_media_get_meta(self, e_meta)
+
+ if hasattr(dll, 'libvlc_media_set_meta'):
+ def set_meta(self, e_meta, psz_value):
+ """Set the meta of the media (this function will not save the meta, call
+libvlc_media_save_meta in order to save the meta)
+@param e_meta: the meta to write
+@param psz_value: the media's meta
+ """
+ return libvlc_media_set_meta(self, e_meta, psz_value)
+
+ if hasattr(dll, 'libvlc_media_save_meta'):
+ def save_meta(self):
+ """Save the meta previously set
+@return: true if the write operation was successfull
+ """
+ return libvlc_media_save_meta(self)
+
+ if hasattr(dll, 'libvlc_media_get_state'):
+ def get_state(self):
+ """Get current state of media descriptor object. Possible media states
+are defined in libvlc_structures.c ( libvlc_NothingSpecial=0,
+libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused,
+libvlc_Stopped, libvlc_Ended,
+libvlc_Error).
+See libvlc_state_t
+@return: state of media descriptor object
+ """
+ return libvlc_media_get_state(self)
+
+ if hasattr(dll, 'libvlc_media_get_stats'):
+ def get_stats(self, p_stats):
+ """Get the current statistics about the media
+ (this structure must be allocated by the caller)
+@param p_stats:: structure that contain the statistics about the media
+@return: true if the statistics are available, false otherwise
+ """
+ return libvlc_media_get_stats(self, p_stats)
+
+ if hasattr(dll, 'libvlc_media_subitems'):
+ def subitems(self):
+ """Get subitems of media descriptor object. This will increment
+the reference count of supplied media descriptor object. Use
+libvlc_media_list_release() to decrement the reference counting.
+and this is here for convenience */
+@return: list of media descriptor subitems or NULL
+ """
+ return libvlc_media_subitems(self)
+
+ if hasattr(dll, 'libvlc_media_event_manager'):
+ def event_manager(self):
+ """Get event manager from media descriptor object.
+NOTE: this function doesn't increment reference counting.
+@return: event manager object
+ """
+ return libvlc_media_event_manager(self)
+
+ if hasattr(dll, 'libvlc_media_get_duration'):
+ def get_duration(self):
+ """Get duration (in ms) of media descriptor object item.
+@return: duration of media item or -1 on error
+ """
+ return libvlc_media_get_duration(self)
+
+ if hasattr(dll, 'libvlc_media_parse'):
+ def parse(self):
+ """Parse a media.
+This fetches (local) meta data and tracks information.
+The method is synchronous.
+See libvlc_media_parse_async
+See libvlc_media_get_meta
+See libvlc_media_get_tracks_info
+ """
+ return libvlc_media_parse(self)
+
+ if hasattr(dll, 'libvlc_media_parse_async'):
+ def parse_async(self):
+ """Parse a media.
+This fetches (local) meta data and tracks information.
+The method is the asynchronous of libvlc_media_parse().
+To track when this is over you can listen to libvlc_MediaParsedChanged
+event. However if the media was already parsed you will not receive this
+event.
+See libvlc_media_parse
+See libvlc_MediaParsedChanged
+See libvlc_media_get_meta
+See libvlc_media_get_tracks_info
+ """
+ return libvlc_media_parse_async(self)
+
+ if hasattr(dll, 'libvlc_media_is_parsed'):
+ def is_parsed(self):
+ """Get Parsed status for media descriptor object.
+See libvlc_MediaParsedChanged
+@return: true if media object has been parsed otherwise it returns false
+ """
+ return libvlc_media_is_parsed(self)
+
+ if hasattr(dll, 'libvlc_media_set_user_data'):
+ def set_user_data(self, p_new_user_data):
+ """Sets media descriptor's user_data. user_data is specialized data
+accessed by the host application, VLC.framework uses it as a pointer to
+an native object that references a libvlc_media_t pointer
+@param p_new_user_data: pointer to user data
+ """
+ return libvlc_media_set_user_data(self, p_new_user_data)
+
+ if hasattr(dll, 'libvlc_media_get_user_data'):
+ def get_user_data(self):
+ """Get media descriptor's user_data. user_data is specialized data
+accessed by the host application, VLC.framework uses it as a pointer to
+an native object that references a libvlc_media_t pointer
+ """
+ return libvlc_media_get_user_data(self)
+
+ if hasattr(dll, 'libvlc_media_get_tracks_info'):
+ def get_tracks_info(self, tracks):
+ """Get media descriptor's elementary streams description
+Note, you need to play the media _one_ time with --sout="#description"
+Not doing this will result in an empty array, and doing it more than once
+will duplicate the entries in the array each time. Something like this:
+@begincode
+libvlc_media_player_t *player = libvlc_media_player_new_from_media(media);
+libvlc_media_add_option_flag(media, "sout=#description");
+libvlc_media_player_play(player);
+// ... wait until playing
+libvlc_media_player_release(player);
+@endcode
+This is very likely to change in next release, and be done at the parsing
+phase.
+descriptions (must be freed by the caller)
+return the number of Elementary Streams
+@param tracks: address to store an allocated array of Elementary Streams
+ """
+ return libvlc_media_get_tracks_info(self, tracks)
+
+ if hasattr(dll, 'libvlc_media_player_new_from_media'):
+ def player_new_from_media(self):
+ """Create a Media Player object from a Media
+ destroyed.
+@return: a new media player object, or NULL on error.
+ """
+ return libvlc_media_player_new_from_media(self)
+
+class MediaDiscoverer(object):
+
+ def __new__(cls, pointer=None):
+ '''Internal method used for instanciating wrappers from ctypes.
+ '''
+ if pointer is None:
+ raise Exception("Internal method. Surely this class cannot be instanciated by itself.")
+ if pointer == 0:
+ return None
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(pointer)
+ return o
+
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+ if hasattr(dll, 'libvlc_media_discoverer_release'):
+ def release(self):
+ """Release media discover object. If the reference count reaches 0, then
+the object will be released.
+ """
+ return libvlc_media_discoverer_release(self)
+
+ if hasattr(dll, 'libvlc_media_discoverer_localized_name'):
+ def localized_name(self):
+ """Get media service discover object its localized name.
+@return: localized name
+ """
+ return libvlc_media_discoverer_localized_name(self)
+
+ if hasattr(dll, 'libvlc_media_discoverer_media_list'):
+ def media_list(self):
+ """Get media service discover media list.
+@return: list of media items
+ """
+ return libvlc_media_discoverer_media_list(self)
+
+ if hasattr(dll, 'libvlc_media_discoverer_event_manager'):
+ def event_manager(self):
+ """Get event manager from media service discover object.
+@return: event manager object.
+ """
+ return libvlc_media_discoverer_event_manager(self)
+
+ if hasattr(dll, 'libvlc_media_discoverer_is_running'):
+ def is_running(self):
+ """Query if media service discover object is running.
+@return: true if running, false if not
+ """
+ return libvlc_media_discoverer_is_running(self)
+
+class MediaLibrary(object):
+
+ def __new__(cls, pointer=None):
+ '''Internal method used for instanciating wrappers from ctypes.
+ '''
+ if pointer is None:
+ raise Exception("Internal method. Surely this class cannot be instanciated by itself.")
+ if pointer == 0:
+ return None
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(pointer)
+ return o
+
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+ if hasattr(dll, 'libvlc_media_library_release'):
+ def release(self):
+ """Release media library object. This functions decrements the
+reference count of the media library object. If it reaches 0,
+then the object will be released.
+ """
+ return libvlc_media_library_release(self)
+
+ if hasattr(dll, 'libvlc_media_library_retain'):
+ def retain(self):
+ """Retain a reference to a media library object. This function will
+increment the reference counting for this object. Use
+libvlc_media_library_release() to decrement the reference count.
+ """
+ return libvlc_media_library_retain(self)
+
+ if hasattr(dll, 'libvlc_media_library_load'):
+ def load(self):
+ """Load media library.
+@return: 0 on success, -1 on error
+ """
+ return libvlc_media_library_load(self)
+
+ if hasattr(dll, 'libvlc_media_library_media_list'):
+ def media_list(self):
+ """Get media library subitems.
+@return: media list subitems
+ """
+ return libvlc_media_library_media_list(self)
+
+class MediaList(object):
+
+ def __new__(cls, pointer=None):
+ '''Internal method used for instanciating wrappers from ctypes.
+ '''
+ if pointer is None:
+ raise Exception("Internal method. Surely this class cannot be instanciated by itself.")
+ if pointer == 0:
+ return None
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(pointer)
+ return o
+
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+ if hasattr(dll, 'libvlc_media_list_release'):
+ def release(self):
+ """Release media list created with libvlc_media_list_new().
+ """
+ return libvlc_media_list_release(self)
+
+ if hasattr(dll, 'libvlc_media_list_retain'):
+ def retain(self):
+ """Retain reference to a media list
+ """
+ return libvlc_media_list_retain(self)
+
+ if hasattr(dll, 'libvlc_media_list_set_media'):
+ def set_media(self, p_md):
+ """Associate media instance with this media list instance.
+If another media instance was present it will be released.
+The libvlc_media_list_lock should NOT be held upon entering this function.
+@param p_md: media instance to add
+ """
+ return libvlc_media_list_set_media(self, p_md)
+
+ if hasattr(dll, 'libvlc_media_list_media'):
+ def media(self):
+ """Get media instance from this media list instance. This action will increase
+the refcount on the media instance.
+The libvlc_media_list_lock should NOT be held upon entering this function.
+@return: media instance
+ """
+ return libvlc_media_list_media(self)
+
+ if hasattr(dll, 'libvlc_media_list_add_media'):
+ def add_media(self, p_md):
+ """Add media instance to media list
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_md: a media instance
+@return: 0 on success, -1 if the media list is read-only
+ """
+ return libvlc_media_list_add_media(self, p_md)
+
+ if hasattr(dll, 'libvlc_media_list_insert_media'):
+ def insert_media(self, p_md, i_pos):
+ """Insert media instance in media list on a position
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_md: a media instance
+@param i_pos: position in array where to insert
+@return: 0 on success, -1 if the media list si read-only
+ """
+ return libvlc_media_list_insert_media(self, p_md, i_pos)
+
+ if hasattr(dll, 'libvlc_media_list_remove_index'):
+ def remove_index(self, i_pos):
+ """Remove media instance from media list on a position
+The libvlc_media_list_lock should be held upon entering this function.
+@param i_pos: position in array where to insert
+@return: 0 on success, -1 if the list is read-only or the item was not found
+ """
+ return libvlc_media_list_remove_index(self, i_pos)
+
+ if hasattr(dll, 'libvlc_media_list_count'):
+ def count(self):
+ """Get count on media list items
+The libvlc_media_list_lock should be held upon entering this function.
+@return: number of items in media list
+ """
+ return libvlc_media_list_count(self)
+
+ def __len__(self):
+ return libvlc_media_list_count(self)
+
+ if hasattr(dll, 'libvlc_media_list_item_at_index'):
+ def item_at_index(self, i_pos):
+ """List media instance in media list at a position
+The libvlc_media_list_lock should be held upon entering this function.
+In case of success, libvlc_media_retain() is called to increase the refcount
+on the media.
+@param i_pos: position in array where to insert
+@return: media instance at position i_pos, or NULL if not found.
+ """
+ return libvlc_media_list_item_at_index(self, i_pos)
+
+ def __getitem__(self, i):
+ return libvlc_media_list_item_at_index(self, i)
+
+ def __iter__(self):
+ for i in xrange(len(self)):
+ yield self[i]
+
+ if hasattr(dll, 'libvlc_media_list_index_of_item'):
+ def index_of_item(self, p_md):
+ """Find index position of List media instance in media list.
+Warning: the function will return the first matched position.
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_md: media list instance
+@return: position of media instance
+ """
+ return libvlc_media_list_index_of_item(self, p_md)
+
+ if hasattr(dll, 'libvlc_media_list_is_readonly'):
+ def is_readonly(self):
+ """This indicates if this media list is read-only from a user point of view
+@return: 0 on readonly, 1 on readwrite
+ """
+ return libvlc_media_list_is_readonly(self)
+
+ if hasattr(dll, 'libvlc_media_list_lock'):
+ def lock(self):
+ """Get lock on media list items
+ """
+ return libvlc_media_list_lock(self)
+
+ if hasattr(dll, 'libvlc_media_list_unlock'):
+ def unlock(self):
+ """Release lock on media list items
+The libvlc_media_list_lock should be held upon entering this function.
+ """
+ return libvlc_media_list_unlock(self)
+
+ if hasattr(dll, 'libvlc_media_list_event_manager'):
+ def event_manager(self):
+ """Get libvlc_event_manager from this media list instance.
+The p_event_manager is immutable, so you don't have to hold the lock
+@return: libvlc_event_manager
+ """
+ return libvlc_media_list_event_manager(self)
+
+class MediaListPlayer(object):
+ """Create a new MediaListPlayer instance.
+
+ It may take as parameter either:
+ - a vlc.Instance
+ - nothing
+ """
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+
+ def __new__(cls, *p):
+ if p and p[0] == 0:
+ return None
+ elif p and isinstance(p[0], (int, long)):
+ # instance creation from ctypes
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(p[0])
+ return o
+ elif len(p) == 1 and isinstance(p[0], (tuple, list)):
+ p=p[0]
+
+ if p and isinstance(p[0], Instance):
+ return p[0].media_list_player_new()
+ else:
+ i=Instance()
+ o=i.media_list_player_new()
+ return o
+
+ def get_instance(self):
+ """Return the associated vlc.Instance.
+ """
+ return self._instance
+
+
+ if hasattr(dll, 'libvlc_media_list_player_release'):
+ def release(self):
+ """Release media_list_player.
+ """
+ return libvlc_media_list_player_release(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_event_manager'):
+ def event_manager(self):
+ """Return the event manager of this media_list_player.
+@return: the event manager
+ """
+ return libvlc_media_list_player_event_manager(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_set_media_player'):
+ def set_media_player(self, p_mi):
+ """Replace media player in media_list_player with this instance.
+@param p_mi: media player instance
+ """
+ return libvlc_media_list_player_set_media_player(self, p_mi)
+
+ if hasattr(dll, 'libvlc_media_list_player_set_media_list'):
+ def set_media_list(self, p_mlist):
+ """Set the media list associated with the player
+@param p_mlist: list of media
+ """
+ return libvlc_media_list_player_set_media_list(self, p_mlist)
+
+ if hasattr(dll, 'libvlc_media_list_player_play'):
+ def play(self):
+ """Play media list
+ """
+ return libvlc_media_list_player_play(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_pause'):
+ def pause(self):
+ """Pause media list
+ """
+ return libvlc_media_list_player_pause(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_is_playing'):
+ def is_playing(self):
+ """Is media list playing?
+@return: true for playing and false for not playing
+ """
+ return libvlc_media_list_player_is_playing(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_get_state'):
+ def get_state(self):
+ """Get current libvlc_state of media list player
+@return: libvlc_state_t for media list player
+ """
+ return libvlc_media_list_player_get_state(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_play_item_at_index'):
+ def play_item_at_index(self, i_index):
+ """Play media list item at position index
+@param i_index: index in media list to play
+@return: 0 upon success -1 if the item wasn't found
+ """
+ return libvlc_media_list_player_play_item_at_index(self, i_index)
+
+ def __getitem__(self, i):
+ return libvlc_media_list_player_play_item_at_index(self, i)
+
+ def __iter__(self):
+ for i in xrange(len(self)):
+ yield self[i]
+
+ if hasattr(dll, 'libvlc_media_list_player_play_item'):
+ def play_item(self, p_md):
+ """Play the given media item
+@param p_md: the media instance
+@return: 0 upon success, -1 if the media is not part of the media list
+ """
+ return libvlc_media_list_player_play_item(self, p_md)
+
+ if hasattr(dll, 'libvlc_media_list_player_stop'):
+ def stop(self):
+ """Stop playing media list
+ """
+ return libvlc_media_list_player_stop(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_next'):
+ def next(self):
+ """Play next item from media list
+@return: 0 upon success -1 if there is no next item
+ """
+ return libvlc_media_list_player_next(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_previous'):
+ def previous(self):
+ """Play previous item from media list
+@return: 0 upon success -1 if there is no previous item
+ """
+ return libvlc_media_list_player_previous(self)
+
+ if hasattr(dll, 'libvlc_media_list_player_set_playback_mode'):
+ def set_playback_mode(self, e_mode):
+ """Sets the playback mode for the playlist
+@param e_mode: playback mode specification
+ """
+ return libvlc_media_list_player_set_playback_mode(self, e_mode)
+
+class MediaPlayer(object):
+ """Create a new MediaPlayer instance.
+
+ It may take as parameter either:
+ - a string (media URI). In this case, a vlc.Instance will be created.
+ - a vlc.Instance
+ """
+
+ @staticmethod
+ def from_param(arg):
+ '''(INTERNAL) ctypes parameter conversion method.
+ '''
+ return arg._as_parameter_
+
+
+ def __new__(cls, *p):
+ if p and p[0] == 0:
+ return None
+ elif p and isinstance(p[0], (int, long)):
+ # instance creation from ctypes
+ o=object.__new__(cls)
+ o._as_parameter_=ctypes.c_void_p(p[0])
+ return o
+
+ if p and isinstance(p[0], Instance):
+ return p[0].media_player_new()
+ else:
+ i=Instance()
+ o=i.media_player_new()
+ if p:
+ o.set_media(i.media_new(p[0]))
+ return o
+
+ def get_instance(self):
+ """Return the associated vlc.Instance.
+ """
+ return self._instance
+
+ def set_mrl(self, mrl, *options):
+ """Set the MRL to play.
+
+ @param mrl: The MRL
+ @param options: a list of options
+ @return The Media object
+ """
+ m = self.get_instance().media_new(mrl, *options)
+ self.set_media(m)
+ return m
+
+ def video_get_spu_description(self):
+ """Get the description of available video subtitles.
+ """
+ return track_description_list(libvlc_video_get_spu_description(self))
+
+ def video_get_title_description(self):
+ """Get the description of available titles.
+ """
+ return track_description_list(libvlc_video_get_title_description(self))
+
+ def video_get_chapter_description(self, title):
+ """Get the description of available chapters for specific title.
+ @param i_title selected title (int)
+ """
+ return track_description_list(libvlc_video_get_chapter_description(self, title))
+
+ def video_get_track_description(self):
+ """Get the description of available video tracks.
+ """
+ return track_description_list(libvlc_video_get_track_description(self))
+
+ def audio_get_track_description(self):
+ """Get the description of available audio tracks.
+ """
+ return track_description_list(libvlc_audio_get_track_description(self))
+
+ def video_get_width(self, num=0):
+ """Get the width of a video in pixels.
+
+ @param num: video number (default 0)
+ """
+ return self.video_get_size(num)[0]
+
+ def video_get_height(self, num=0):
+ """Get the height of a video in pixels.
+
+ @param num: video number (default 0)
+ """
+ return self.video_get_size(num)[1]
+
+
+ if hasattr(dll, 'libvlc_media_player_release'):
+ def release(self):
+ """Release a media_player after use
+Decrement the reference count of a media player object. If the
+reference count is 0, then libvlc_media_player_release() will
+release the media player object. If the media player object
+has been released, then it should not be used again.
+ """
+ return libvlc_media_player_release(self)
+
+ if hasattr(dll, 'libvlc_media_player_retain'):
+ def retain(self):
+ """Retain a reference to a media player object. Use
+libvlc_media_player_release() to decrement reference count.
+ """
+ return libvlc_media_player_retain(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_media'):
+ def set_media(self, p_md):
+ """Set the media that will be used by the media_player. If any,
+previous md will be released.
+ destroyed.
+@param p_md: the Media. Afterwards the p_md can be safely
+ """
+ return libvlc_media_player_set_media(self, p_md)
+
+ if hasattr(dll, 'libvlc_media_player_get_media'):
+ def get_media(self):
+ """Get the media used by the media_player.
+ media is associated
+@return: the media associated with p_mi, or NULL if no
+ """
+ return libvlc_media_player_get_media(self)
+
+ if hasattr(dll, 'libvlc_media_player_event_manager'):
+ def event_manager(self):
+ """Get the Event Manager from which the media player send event.
+@return: the event manager associated with p_mi
+ """
+ return libvlc_media_player_event_manager(self)
+
+ if hasattr(dll, 'libvlc_media_player_is_playing'):
+ def is_playing(self):
+ """is_playing
+@return: 1 if the media player is playing, 0 otherwise
+ """
+ return libvlc_media_player_is_playing(self)
+
+ if hasattr(dll, 'libvlc_media_player_play'):
+ def play(self):
+ """Play
+@return: 0 if playback started (and was already started), or -1 on error.
+ """
+ return libvlc_media_player_play(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_pause'):
+ def set_pause(self, do_pause):
+ """Pause or resume (no effect if there is no media)
+@version: LibVLC 1.1.1 or later
+@param do_pause: play/resume if zero, pause if non-zero
+ """
+ return libvlc_media_player_set_pause(self, do_pause)
+
+ if hasattr(dll, 'libvlc_media_player_pause'):
+ def pause(self):
+ """Toggle pause (no effect if there is no media)
+ """
+ return libvlc_media_player_pause(self)
+
+ if hasattr(dll, 'libvlc_media_player_stop'):
+ def stop(self):
+ """Stop (no effect if there is no media)
+ """
+ return libvlc_media_player_stop(self)
+
+ if hasattr(dll, 'libvlc_video_set_format'):
+ def video_set_format(self, chroma, width, height, pitch):
+ """Set decoded video chroma and dimensions. This only works in combination with
+libvlc_video_set_callbacks().
+ (e.g. "RV32" or "I420")
+@version: LibVLC 1.1.1 or later
+@param chroma: a four-characters string identifying the chroma
+@param width: pixel width
+@param height: pixel height
+@param pitch: line pitch (in bytes)
+ """
+ return libvlc_video_set_format(self, chroma, width, height, pitch)
+
+ if hasattr(dll, 'libvlc_media_player_set_nsobject'):
+ def set_nsobject(self, drawable):
+ """Set the NSView handler where the media player should render its video output.
+Use the vout called "macosx".
+The drawable is an NSObject that follow the VLCOpenGLVideoViewEmbedding
+protocol:
+@begincode
+\@protocol VLCOpenGLVideoViewEmbedding <NSObject>
+- (void)addVoutSubview:(NSView *)view;
+- (void)removeVoutSubview:(NSView *)view;
+\@end
+@endcode
+Or it can be an NSView object.
+If you want to use it along with Qt4 see the QMacCocoaViewContainer. Then
+the following code should work:
+@begincode
+{
+ NSView *video = [[NSView alloc] init];
+ QMacCocoaViewContainer *container = new QMacCocoaViewContainer(video, parent);
+ libvlc_media_player_set_nsobject(mp, video);
+ [video release];
+}
+@endcode
+You can find a live example in VLCVideoView in VLCKit.framework.
+the VLCOpenGLVideoViewEmbedding protocol.
+@param drawable: the drawable that is either an NSView or an object following
+ """
+ return libvlc_media_player_set_nsobject(self, drawable)
+
+ if hasattr(dll, 'libvlc_media_player_get_nsobject'):
+ def get_nsobject(self):
+ """Get the NSView handler previously set with libvlc_media_player_set_nsobject().
+@return: the NSView handler or 0 if none where set
+ """
+ return libvlc_media_player_get_nsobject(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_agl'):
+ def set_agl(self, drawable):
+ """Set the agl handler where the media player should render its video output.
+@param drawable: the agl handler
+ """
+ return libvlc_media_player_set_agl(self, drawable)
+
+ if hasattr(dll, 'libvlc_media_player_get_agl'):
+ def get_agl(self):
+ """Get the agl handler previously set with libvlc_media_player_set_agl().
+@return: the agl handler or 0 if none where set
+ """
+ return libvlc_media_player_get_agl(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_xwindow'):
+ def set_xwindow(self, drawable):
+ """Set an X Window System drawable where the media player should render its
+video output. If LibVLC was built without X11 output support, then this has
+no effects.
+The specified identifier must correspond to an existing Input/Output class
+X11 window. Pixmaps are <b>not</b> supported. The caller shall ensure that
+the X11 server is the same as the one the VLC instance has been configured
+with.
+@param drawable: the ID of the X window
+ """
+ return libvlc_media_player_set_xwindow(self, drawable)
+
+ if hasattr(dll, 'libvlc_media_player_get_xwindow'):
+ def get_xwindow(self):
+ """Get the X Window System window identifier previously set with
+libvlc_media_player_set_xwindow(). Note that this will return the identifier
+even if VLC is not currently using it (for instance if it is playing an
+audio-only input).
+@return: an X window ID, or 0 if none where set.
+ """
+ return libvlc_media_player_get_xwindow(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_hwnd'):
+ def set_hwnd(self, drawable):
+ """Set a Win32/Win64 API window handle (HWND) where the media player should
+render its video output. If LibVLC was built without Win32/Win64 API output
+support, then this has no effects.
+@param drawable: windows handle of the drawable
+ """
+ return libvlc_media_player_set_hwnd(self, drawable)
+
+ if hasattr(dll, 'libvlc_media_player_get_hwnd'):
+ def get_hwnd(self):
+ """Get the Windows API window handle (HWND) previously set with
+libvlc_media_player_set_hwnd(). The handle will be returned even if LibVLC
+is not currently outputting any video to it.
+@return: a window handle or NULL if there are none.
+ """
+ return libvlc_media_player_get_hwnd(self)
+
+ if hasattr(dll, 'libvlc_media_player_get_length'):
+ def get_length(self):
+ """Get the current movie length (in ms).
+@return: the movie length (in ms), or -1 if there is no media.
+ """
+ return libvlc_media_player_get_length(self)
+
+ if hasattr(dll, 'libvlc_media_player_get_time'):
+ def get_time(self):
+ """Get the current movie time (in ms).
+@return: the movie time (in ms), or -1 if there is no media.
+ """
+ return libvlc_media_player_get_time(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_time'):
+ def set_time(self, i_time):
+ """Set the movie time (in ms). This has no effect if no media is being played.
+Not all formats and protocols support this.
+@param i_time: the movie time (in ms).
+ """
+ return libvlc_media_player_set_time(self, i_time)
+
+ if hasattr(dll, 'libvlc_media_player_get_position'):
+ def get_position(self):
+ """Get movie position.
+@return: movie position, or -1. in case of error
+ """
+ return libvlc_media_player_get_position(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_position'):
+ def set_position(self, f_pos):
+ """Set movie position. This has no effect if playback is not enabled.
+This might not work depending on the underlying input format and protocol.
+@param f_pos: the position
+ """
+ return libvlc_media_player_set_position(self, f_pos)
+
+ if hasattr(dll, 'libvlc_media_player_set_chapter'):
+ def set_chapter(self, i_chapter):
+ """Set movie chapter (if applicable).
+@param i_chapter: chapter number to play
+ """
+ return libvlc_media_player_set_chapter(self, i_chapter)
+
+ if hasattr(dll, 'libvlc_media_player_get_chapter'):
+ def get_chapter(self):
+ """Get movie chapter.
+@return: chapter number currently playing, or -1 if there is no media.
+ """
+ return libvlc_media_player_get_chapter(self)
+
+ if hasattr(dll, 'libvlc_media_player_get_chapter_count'):
+ def get_chapter_count(self):
+ """Get movie chapter count
+@return: number of chapters in movie, or -1.
+ """
+ return libvlc_media_player_get_chapter_count(self)
+
+ if hasattr(dll, 'libvlc_media_player_will_play'):
+ def will_play(self):
+ """Is the player able to play
+@return: boolean
+ """
+ return libvlc_media_player_will_play(self)
+
+ if hasattr(dll, 'libvlc_media_player_get_chapter_count_for_title'):
+ def get_chapter_count_for_title(self, i_title):
+ """Get title chapter count
+@param i_title: title
+@return: number of chapters in title, or -1
+ """
+ return libvlc_media_player_get_chapter_count_for_title(self, i_title)
+
+ if hasattr(dll, 'libvlc_media_player_set_title'):
+ def set_title(self, i_title):
+ """Set movie title
+@param i_title: title number to play
+ """
+ return libvlc_media_player_set_title(self, i_title)
+
+ if hasattr(dll, 'libvlc_media_player_get_title'):
+ def get_title(self):
+ """Get movie title
+@return: title number currently playing, or -1
+ """
+ return libvlc_media_player_get_title(self)
+
+ if hasattr(dll, 'libvlc_media_player_get_title_count'):
+ def get_title_count(self):
+ """Get movie title count
+@return: title number count, or -1
+ """
+ return libvlc_media_player_get_title_count(self)
+
+ if hasattr(dll, 'libvlc_media_player_previous_chapter'):
+ def previous_chapter(self):
+ """Set previous chapter (if applicable)
+ """
+ return libvlc_media_player_previous_chapter(self)
+
+ if hasattr(dll, 'libvlc_media_player_next_chapter'):
+ def next_chapter(self):
+ """Set next chapter (if applicable)
+ """
+ return libvlc_media_player_next_chapter(self)
+
+ if hasattr(dll, 'libvlc_media_player_get_rate'):
+ def get_rate(self):
+ """Get the requested movie play rate.
+@warning Depending on the underlying media, the requested rate may be
+different from the real playback rate.
+@return: movie play rate
+ """
+ return libvlc_media_player_get_rate(self)
+
+ if hasattr(dll, 'libvlc_media_player_set_rate'):
+ def set_rate(self, rate):
+ """Set movie play rate
+not actually work depending on the underlying media protocol)
+@param rate: movie play rate to set
+@return: -1 if an error was detected, 0 otherwise (but even then, it might
+ """
+ return libvlc_media_player_set_rate(self, rate)
+
+ if hasattr(dll, 'libvlc_media_player_get_state'):
+ def get_state(self):
+ """Get current movie state
+@return: the current state of the media player (playing, paused, ...) See libvlc_state_t
+ """
+ return libvlc_media_player_get_state(self)
+
+ if hasattr(dll, 'libvlc_media_player_get_fps'):
+ def get_fps(self):
+ """Get movie fps rate
+@return: frames per second (fps) for this playing movie, or 0 if unspecified
+ """
+ return libvlc_media_player_get_fps(self)
+
+ if hasattr(dll, 'libvlc_media_player_has_vout'):
+ def has_vout(self):
+ """How many video outputs does this media player have?
+@return: the number of video outputs
+ """
+ return libvlc_media_player_has_vout(self)
+
+ if hasattr(dll, 'libvlc_media_player_is_seekable'):
+ def is_seekable(self):
+ """Is this media player seekable?
+@return: true if the media player can seek
+ """
+ return libvlc_media_player_is_seekable(self)
+
+ if hasattr(dll, 'libvlc_media_player_can_pause'):
+ def can_pause(self):
+ """Can this media player be paused?
+@return: true if the media player can pause
+ """
+ return libvlc_media_player_can_pause(self)
+
+ if hasattr(dll, 'libvlc_media_player_next_frame'):
+ def next_frame(self):
+ """Display the next frame (if supported)
+ """
+ return libvlc_media_player_next_frame(self)
+
+ if hasattr(dll, 'libvlc_media_player_navigate'):
+ def navigate(self, navigate):
+ """Navigate through DVD Menu
+@version: libVLC 1.2.0 or later
+@param navigate: the Navigation mode
+ """
+ return libvlc_media_player_navigate(self, navigate)
+
+ if hasattr(dll, 'libvlc_toggle_fullscreen'):
+ def toggle_fullscreen(self):
+ """Toggle fullscreen status on non-embedded video outputs.
+@warning The same limitations applies to this function
+as to libvlc_set_fullscreen().
+ """
+ return libvlc_toggle_fullscreen(self)
+
+ if hasattr(dll, 'libvlc_set_fullscreen'):
+ def set_fullscreen(self, b_fullscreen):
+ """Enable or disable fullscreen.
+@warning With most window managers, only a top-level windows can be in
+full-screen mode. Hence, this function will not operate properly if
+libvlc_media_player_set_xwindow() was used to embed the video in a
+non-top-level window. In that case, the embedding window must be reparented
+to the root window <b>before</b> fullscreen mode is enabled. You will want
+to reparent it back to its normal parent when disabling fullscreen.
+@param b_fullscreen: boolean for fullscreen status
+ """
+ return libvlc_set_fullscreen(self, b_fullscreen)
+
+ if hasattr(dll, 'libvlc_get_fullscreen'):
+ def get_fullscreen(self):
+ """Get current fullscreen status.
+@return: the fullscreen status (boolean)
+ """
+ return libvlc_get_fullscreen(self)
+
+ if hasattr(dll, 'libvlc_video_set_key_input'):
+ def video_set_key_input(self, on):
+ """Enable or disable key press events handling, according to the LibVLC hotkeys
+configuration. By default and for historical reasons, keyboard events are
+handled by the LibVLC video widget.
+@note: On X11, there can be only one subscriber for key press and mouse
+click events per window. If your application has subscribed to those events
+for the X window ID of the video widget, then LibVLC will not be able to
+handle key presses and mouse clicks in any case.
+@warning: This function is only implemented for X11 and Win32 at the moment.
+@param on: true to handle key press events, false to ignore them.
+ """
+ return libvlc_video_set_key_input(self, on)
+
+ if hasattr(dll, 'libvlc_video_set_mouse_input'):
+ def video_set_mouse_input(self, on):
+ """Enable or disable mouse click events handling. By default, those events are
+handled. This is needed for DVD menus to work, as well as a few video
+filters such as "puzzle".
+@note: See also libvlc_video_set_key_input().
+@warning: This function is only implemented for X11 and Win32 at the moment.
+@param on: true to handle mouse click events, false to ignore them.
+ """
+ return libvlc_video_set_mouse_input(self, on)
+
+ if hasattr(dll, 'libvlc_video_get_size'):
+ def video_get_size(self, num):
+ """Get the pixel dimensions of a video.
+@param num: number of the video (starting from, and most commonly 0)
+@return x, y
+ """
+ return libvlc_video_get_size(self, num)
+
+ if hasattr(dll, 'libvlc_video_get_cursor'):
+ def video_get_cursor(self, num):
+ """Get the mouse pointer coordinates over a video.
+Coordinates are expressed in terms of the decoded video resolution,
+<b>not</b> in terms of pixels on the screen/viewport (to get the latter,
+you can query your windowing system directly).
+Either of the coordinates may be negative or larger than the corresponding
+dimension of the video, if the cursor is outside the rendering area.
+@warning The coordinates may be out-of-date if the pointer is not located
+on the video rendering area. LibVLC does not track the pointer if it is
+outside of the video widget.
+@note LibVLC does not support multiple pointers (it does of course support
+multiple input devices sharing the same pointer) at the moment.
+@param num: number of the video (starting from, and most commonly 0)
+@return x, y
+ """
+ return libvlc_video_get_cursor(self, num)
+
+ if hasattr(dll, 'libvlc_video_get_scale'):
+ def video_get_scale(self):
+ """Get the current video scaling factor.
+See also libvlc_video_set_scale().
+to fit to the output window/drawable automatically.
+@return: the currently configured zoom factor, or 0. if the video is set
+ """
+ return libvlc_video_get_scale(self)
+
+ if hasattr(dll, 'libvlc_video_set_scale'):
+ def video_set_scale(self, f_factor):
+ """Set the video scaling factor. That is the ratio of the number of pixels on
+screen to the number of pixels in the original decoded video in each
+dimension. Zero is a special value; it will adjust the video to the output
+window/drawable (in windowed mode) or the entire screen.
+Note that not all video outputs support scaling.
+@param f_factor: the scaling factor, or zero
+ """
+ return libvlc_video_set_scale(self, f_factor)
+
+ if hasattr(dll, 'libvlc_video_get_aspect_ratio'):
+ def video_get_aspect_ratio(self):
+ """Get current video aspect ratio.
+(the result must be released with free() or libvlc_free()).
+@return: the video aspect ratio or NULL if unspecified
+ """
+ return libvlc_video_get_aspect_ratio(self)
+
+ if hasattr(dll, 'libvlc_video_set_aspect_ratio'):
+ def video_set_aspect_ratio(self, psz_aspect):
+ """Set new video aspect ratio.
+@note: Invalid aspect ratios are ignored.
+@param psz_aspect: new video aspect-ratio or NULL to reset to default
+ """
+ return libvlc_video_set_aspect_ratio(self, psz_aspect)
+
+ if hasattr(dll, 'libvlc_video_get_spu'):
+ def video_get_spu(self):
+ """Get current video subtitle.
+@return: the video subtitle selected, or -1 if none
+ """
+ return libvlc_video_get_spu(self)
+
+ if hasattr(dll, 'libvlc_video_get_spu_count'):
+ def video_get_spu_count(self):
+ """Get the number of available video subtitles.
+@return: the number of available video subtitles
+ """
+ return libvlc_video_get_spu_count(self)
+
+ if hasattr(dll, 'libvlc_video_set_spu'):
+ def video_set_spu(self, i_spu):
+ """Set new video subtitle.
+@param i_spu: new video subtitle to select
+@return: 0 on success, -1 if out of range
+ """
+ return libvlc_video_set_spu(self, i_spu)
+
+ if hasattr(dll, 'libvlc_video_set_subtitle_file'):
+ def video_set_subtitle_file(self, psz_subtitle):
+ """Set new video subtitle file.
+@param psz_subtitle: new video subtitle file
+@return: the success status (boolean)
+ """
+ return libvlc_video_set_subtitle_file(self, psz_subtitle)
+
+ if hasattr(dll, 'libvlc_video_get_crop_geometry'):
+ def video_get_crop_geometry(self):
+ """Get current crop filter geometry.
+@return: the crop filter geometry or NULL if unset
+ """
+ return libvlc_video_get_crop_geometry(self)
+
+ if hasattr(dll, 'libvlc_video_set_crop_geometry'):
+ def video_set_crop_geometry(self, psz_geometry):
+ """Set new crop filter geometry.
+@param psz_geometry: new crop filter geometry (NULL to unset)
+ """
+ return libvlc_video_set_crop_geometry(self, psz_geometry)
+
+ if hasattr(dll, 'libvlc_video_get_teletext'):
+ def video_get_teletext(self):
+ """Get current teletext page requested.
+@return: the current teletext page requested.
+ """
+ return libvlc_video_get_teletext(self)
+
+ if hasattr(dll, 'libvlc_video_set_teletext'):
+ def video_set_teletext(self, i_page):
+ """Set new teletext page to retrieve.
+@param i_page: teletex page number requested
+ """
+ return libvlc_video_set_teletext(self, i_page)
+
+ if hasattr(dll, 'libvlc_toggle_teletext'):
+ def toggle_teletext(self):
+ """Toggle teletext transparent status on video output.
+ """
+ return libvlc_toggle_teletext(self)
+
+ if hasattr(dll, 'libvlc_video_get_track_count'):
+ def video_get_track_count(self):
+ """Get number of available video tracks.
+@return: the number of available video tracks (int)
+ """
+ return libvlc_video_get_track_count(self)
+
+ if hasattr(dll, 'libvlc_video_get_track'):
+ def video_get_track(self):
+ """Get current video track.
+@return: the video track (int) or -1 if none
+ """
+ return libvlc_video_get_track(self)
+
+ if hasattr(dll, 'libvlc_video_set_track'):
+ def video_set_track(self, i_track):
+ """Set video track.
+@param i_track: the track (int)
+@return: 0 on success, -1 if out of range
+ """
+ return libvlc_video_set_track(self, i_track)
+
+ if hasattr(dll, 'libvlc_video_take_snapshot'):
+ def video_take_snapshot(self, num, psz_filepath, i_width, i_height):
+ """Take a snapshot of the current video window.
+If i_width AND i_height is 0, original size is used.
+If i_width XOR i_height is 0, original aspect-ratio is preserved.
+@param num: number of video output (typically 0 for the first/only one)
+@param psz_filepath: the path where to save the screenshot to
+@param i_width: the snapshot's width
+@param i_height: the snapshot's height
+@return: 0 on success, -1 if the video was not found
+ """
+ return libvlc_video_take_snapshot(self, num, psz_filepath, i_width, i_height)
+
+ if hasattr(dll, 'libvlc_video_set_deinterlace'):
+ def video_set_deinterlace(self, psz_mode):
+ """Enable or disable deinterlace filter
+@param psz_mode: type of deinterlace filter, NULL to disable
+ """
+ return libvlc_video_set_deinterlace(self, psz_mode)
+
+ if hasattr(dll, 'libvlc_video_get_marquee_int'):
+ def video_get_marquee_int(self, option):
+ """Get an integer marquee option value
+@param option: marq option to get See libvlc_video_marquee_int_option_t
+ """
+ return libvlc_video_get_marquee_int(self, option)
+
+ if hasattr(dll, 'libvlc_video_get_marquee_string'):
+ def video_get_marquee_string(self, option):
+ """Get a string marquee option value
+@param option: marq option to get See libvlc_video_marquee_string_option_t
+ """
+ return libvlc_video_get_marquee_string(self, option)
+
+ if hasattr(dll, 'libvlc_video_set_marquee_int'):
+ def video_set_marquee_int(self, option, i_val):
+ """Enable, disable or set an integer marquee option
+Setting libvlc_marquee_Enable has the side effect of enabling (arg !0)
+or disabling (arg 0) the marq filter.
+@param option: marq option to set See libvlc_video_marquee_int_option_t
+@param i_val: marq option value
+ """
+ return libvlc_video_set_marquee_int(self, option, i_val)
+
+ if hasattr(dll, 'libvlc_video_set_marquee_string'):
+ def video_set_marquee_string(self, option, psz_text):
+ """Set a marquee string option
+@param option: marq option to set See libvlc_video_marquee_string_option_t
+@param psz_text: marq option value
+ """
+ return libvlc_video_set_marquee_string(self, option, psz_text)
+
+ if hasattr(dll, 'libvlc_video_get_logo_int'):
+ def video_get_logo_int(self, option):
+ """Get integer logo option.
+@param option: logo option to get, values of libvlc_video_logo_option_t
+ """
+ return libvlc_video_get_logo_int(self, option)
+
+ if hasattr(dll, 'libvlc_video_set_logo_int'):
+ def video_set_logo_int(self, option, value):
+ """Set logo option as integer. Options that take a different type value
+are ignored.
+Passing libvlc_logo_enable as option value has the side effect of
+starting (arg !0) or stopping (arg 0) the logo filter.
+@param option: logo option to set, values of libvlc_video_logo_option_t
+@param value: logo option value
+ """
+ return libvlc_video_set_logo_int(self, option, value)
+
+ if hasattr(dll, 'libvlc_video_set_logo_string'):
+ def video_set_logo_string(self, option, psz_value):
+ """Set logo option as string. Options that take a different type value
+are ignored.
+@param option: logo option to set, values of libvlc_video_logo_option_t
+@param psz_value: logo option value
+ """
+ return libvlc_video_set_logo_string(self, option, psz_value)
+
+ if hasattr(dll, 'libvlc_video_get_adjust_int'):
+ def video_get_adjust_int(self, option):
+ """Get integer adjust option.
+@version: LibVLC 1.1.1 and later.
+@param option: adjust option to get, values of libvlc_video_adjust_option_t
+ """
+ return libvlc_video_get_adjust_int(self, option)
+
+ if hasattr(dll, 'libvlc_video_set_adjust_int'):
+ def video_set_adjust_int(self, option, value):
+ """Set adjust option as integer. Options that take a different type value
+are ignored.
+Passing libvlc_adjust_enable as option value has the side effect of
+starting (arg !0) or stopping (arg 0) the adjust filter.
+@version: LibVLC 1.1.1 and later.
+@param option: adust option to set, values of libvlc_video_adjust_option_t
+@param value: adjust option value
+ """
+ return libvlc_video_set_adjust_int(self, option, value)
+
+ if hasattr(dll, 'libvlc_video_get_adjust_float'):
+ def video_get_adjust_float(self, option):
+ """Get float adjust option.
+@version: LibVLC 1.1.1 and later.
+@param option: adjust option to get, values of libvlc_video_adjust_option_t
+ """
+ return libvlc_video_get_adjust_float(self, option)
+
+ if hasattr(dll, 'libvlc_video_set_adjust_float'):
+ def video_set_adjust_float(self, option, value):
+ """Set adjust option as float. Options that take a different type value
+are ignored.
+@version: LibVLC 1.1.1 and later.
+@param option: adust option to set, values of libvlc_video_adjust_option_t
+@param value: adjust option value
+ """
+ return libvlc_video_set_adjust_float(self, option, value)
+
+ if hasattr(dll, 'libvlc_audio_output_set'):
+ def audio_output_set(self, psz_name):
+ """Set the audio output.
+Change will be applied after stop and play.
+ use psz_name of See libvlc_audio_output_t
+@param psz_name: name of audio output,
+@return: true if function succeded
+ """
+ return libvlc_audio_output_set(self, psz_name)
+
+ if hasattr(dll, 'libvlc_audio_output_device_set'):
+ def audio_output_device_set(self, psz_audio_output, psz_device_id):
+ """Set audio output device. Changes are only effective after stop and play.
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@param psz_device_id: device
+ """
+ return libvlc_audio_output_device_set(self, psz_audio_output, psz_device_id)
+
+ if hasattr(dll, 'libvlc_audio_output_get_device_type'):
+ def audio_output_get_device_type(self):
+ """Get current audio device type. Device type describes something like
+character of output sound - stereo sound, 2.1, 5.1 etc
+@return: the audio devices type See libvlc_audio_output_device_types_t
+ """
+ return libvlc_audio_output_get_device_type(self)
+
+ if hasattr(dll, 'libvlc_audio_output_set_device_type'):
+ def audio_output_set_device_type(self, device_type):
+ """Set current audio device type.
+@param device_type: the audio device type,
+ """
+ return libvlc_audio_output_set_device_type(self, device_type)
+
+ if hasattr(dll, 'libvlc_audio_toggle_mute'):
+ def audio_toggle_mute(self):
+ """Toggle mute status.
+ """
+ return libvlc_audio_toggle_mute(self)
+
+ if hasattr(dll, 'libvlc_audio_get_mute'):
+ def audio_get_mute(self):
+ """Get current mute status.
+@return: the mute status (boolean)
+ """
+ return libvlc_audio_get_mute(self)
+
+ if hasattr(dll, 'libvlc_audio_set_mute'):
+ def audio_set_mute(self, status):
+ """Set mute status.
+@param status: If status is true then mute, otherwise unmute
+ """
+ return libvlc_audio_set_mute(self, status)
+
+ if hasattr(dll, 'libvlc_audio_get_volume'):
+ def audio_get_volume(self):
+ """Get current audio level.
+@return: the audio level (int)
+ """
+ return libvlc_audio_get_volume(self)
+
+ if hasattr(dll, 'libvlc_audio_set_volume'):
+ def audio_set_volume(self, i_volume):
+ """Set current audio level.
+@param i_volume: the volume (int)
+@return: 0 if the volume was set, -1 if it was out of range
+ """
+ return libvlc_audio_set_volume(self, i_volume)
+
+ if hasattr(dll, 'libvlc_audio_get_track_count'):
+ def audio_get_track_count(self):
+ """Get number of available audio tracks.
+@return: the number of available audio tracks (int), or -1 if unavailable
+ """
+ return libvlc_audio_get_track_count(self)
+
+ if hasattr(dll, 'libvlc_audio_get_track'):
+ def audio_get_track(self):
+ """Get current audio track.
+@return: the audio track (int), or -1 if none.
+ """
+ return libvlc_audio_get_track(self)
+
+ if hasattr(dll, 'libvlc_audio_set_track'):
+ def audio_set_track(self, i_track):
+ """Set current audio track.
+@param i_track: the track (int)
+@return: 0 on success, -1 on error
+ """
+ return libvlc_audio_set_track(self, i_track)
+
+ if hasattr(dll, 'libvlc_audio_get_channel'):
+ def audio_get_channel(self):
+ """Get current audio channel.
+@return: the audio channel See libvlc_audio_output_channel_t
+ """
+ return libvlc_audio_get_channel(self)
+
+ if hasattr(dll, 'libvlc_audio_set_channel'):
+ def audio_set_channel(self, channel):
+ """Set current audio channel.
+@param channel: the audio channel, See libvlc_audio_output_channel_t
+@return: 0 on success, -1 on error
+ """
+ return libvlc_audio_set_channel(self, channel)
+
+ if hasattr(dll, 'libvlc_audio_get_delay'):
+ def audio_get_delay(self):
+ """Get current audio delay.
+@version: LibVLC 1.1.1 or later
+@return: the audio delay (microseconds)
+ """
+ return libvlc_audio_get_delay(self)
+
+ if hasattr(dll, 'libvlc_audio_set_delay'):
+ def audio_set_delay(self, i_delay):
+ """Set current audio delay. The audio delay will be reset to zero each time the media changes.
+@version: LibVLC 1.1.1 or later
+@param i_delay: the audio delay (microseconds)
+@return: 0 on success, -1 on error
+ """
+ return libvlc_audio_set_delay(self, i_delay)
+
+if hasattr(dll, 'libvlc_errmsg'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p)
+ f = ()
+ libvlc_errmsg = p( ('libvlc_errmsg', dll), f )
+ libvlc_errmsg.__doc__ = """A human-readable error message for the last LibVLC error in the calling
+thread. The resulting string is valid until another error occurs (at least
+until the next LibVLC call).
+@warning
+This will be NULL if there was no error.
+"""
+
+if hasattr(dll, 'libvlc_clearerr'):
+ p = ctypes.CFUNCTYPE(None)
+ f = ()
+ libvlc_clearerr = p( ('libvlc_clearerr', dll), f )
+ libvlc_clearerr.__doc__ = """Clears the LibVLC error status for the current thread. This is optional.
+By default, the error status is automatically overridden when a new error
+occurs, and destroyed when the thread exits.
+"""
+
+if hasattr(dll, 'libvlc_new'):
+ p = ctypes.CFUNCTYPE(Instance, ctypes.c_int, ListPOINTER(ctypes.c_char_p))
+ f = ((1,), (1,),)
+ libvlc_new = p( ('libvlc_new', dll), f )
+ libvlc_new.__doc__ = """Create and initialize a libvlc instance.
+This functions accept a list of "command line" arguments similar to the
+main(). These arguments affect the LibVLC instance default configuration.
+@version:
+Arguments are meant to be passed from the command line to LibVLC, just like
+VLC media player does. The list of valid arguments depends on the LibVLC
+version, the operating system and platform, and set of available LibVLC
+plugins. Invalid or unsupported arguments will cause the function to fail
+(i.e. return NULL). Also, some arguments may alter the behaviour or
+otherwise interfere with other LibVLC functions.
+@warning:
+There is absolutely no warranty or promise of forward, backward and
+cross-platform compatibility with regards to libvlc_new() arguments.
+We recommend that you do not use them, other than when debugging.
+@param argc: the number of arguments (should be 0)
+@param argv: list of arguments (should be NULL)
+@return: the libvlc instance or NULL in case of error
+"""
+
+if hasattr(dll, 'libvlc_release'):
+ p = ctypes.CFUNCTYPE(None, Instance)
+ f = ((1,),)
+ libvlc_release = p( ('libvlc_release', dll), f )
+ libvlc_release.__doc__ = """Decrement the reference count of a libvlc instance, and destroy it
+if it reaches zero.
+@param p_instance: the instance to destroy
+"""
+
+if hasattr(dll, 'libvlc_retain'):
+ p = ctypes.CFUNCTYPE(None, Instance)
+ f = ((1,),)
+ libvlc_retain = p( ('libvlc_retain', dll), f )
+ libvlc_retain.__doc__ = """Increments the reference count of a libvlc instance.
+The initial reference count is 1 after libvlc_new() returns.
+@param p_instance: the instance to reference
+"""
+
+if hasattr(dll, 'libvlc_add_intf'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_add_intf = p( ('libvlc_add_intf', dll), f )
+ libvlc_add_intf.__doc__ = """Try to start a user interface for the libvlc instance.
+@param p_instance: the instance
+@param name: interface name, or NULL for default
+@return: 0 on success, -1 on error.
+"""
+
+if hasattr(dll, 'libvlc_wait'):
+ p = ctypes.CFUNCTYPE(None, Instance)
+ f = ((1,),)
+ libvlc_wait = p( ('libvlc_wait', dll), f )
+ libvlc_wait.__doc__ = """Waits until an interface causes the instance to exit.
+You should start at least one interface first, using libvlc_add_intf().
+@param p_instance: the instance
+"""
+
+if hasattr(dll, 'libvlc_set_user_agent'):
+ p = ctypes.CFUNCTYPE(None, Instance, ctypes.c_char_p, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_set_user_agent = p( ('libvlc_set_user_agent', dll), f )
+ libvlc_set_user_agent.__doc__ = """Sets the application name. LibVLC passes this as the user agent string
+when a protocol requires it.
+@version: LibVLC 1.1.1 or later
+@param p_instance: LibVLC instance
+@param name: human-readable application name, e.g. "FooBar player 1.2.3"
+@param http: HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0"
+"""
+
+if hasattr(dll, 'libvlc_get_version'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p)
+ f = ()
+ libvlc_get_version = p( ('libvlc_get_version', dll), f )
+ libvlc_get_version.__doc__ = """Retrieve libvlc version.
+Example: "1.1.0-git The Luggage"
+@return: a string containing the libvlc version
+"""
+
+if hasattr(dll, 'libvlc_get_compiler'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p)
+ f = ()
+ libvlc_get_compiler = p( ('libvlc_get_compiler', dll), f )
+ libvlc_get_compiler.__doc__ = """Retrieve libvlc compiler version.
+Example: "gcc version 4.2.3 (Ubuntu 4.2.3-2ubuntu6)"
+@return: a string containing the libvlc compiler version
+"""
+
+if hasattr(dll, 'libvlc_get_changeset'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p)
+ f = ()
+ libvlc_get_changeset = p( ('libvlc_get_changeset', dll), f )
+ libvlc_get_changeset.__doc__ = """Retrieve libvlc changeset.
+Example: "aa9bce0bc4"
+@return: a string containing the libvlc changeset
+"""
+
+if hasattr(dll, 'libvlc_free'):
+ p = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
+ f = ((1,),)
+ libvlc_free = p( ('libvlc_free', dll), f )
+ libvlc_free.__doc__ = """Frees an heap allocation returned by a LibVLC function.
+If you know you're using the same underlying C run-time as the LibVLC
+implementation, then you can call ANSI C free() directly instead.
+@param ptr: the pointer
+"""
+
+if hasattr(dll, 'libvlc_event_attach'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, EventManager, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p)
+ f = ((1,), (1,), (1,), (1,),)
+ libvlc_event_attach = p( ('libvlc_event_attach', dll), f )
+ libvlc_event_attach.__doc__ = """Register for an event notification.
+ Generally it is obtained by vlc_my_object_event_manager() where
+ my_object is the object you want to listen to.
+@param p_event_manager: the event manager to which you want to attach to.
+@param i_event_type: the desired event to which we want to listen
+@param f_callback: the function to call when i_event_type occurs
+@param user_data: user provided data to carry with the event
+@return: 0 on success, ENOMEM on error
+"""
+
+if hasattr(dll, 'libvlc_event_detach'):
+ p = ctypes.CFUNCTYPE(None, EventManager, ctypes.c_uint, ctypes.c_void_p, ctypes.c_void_p)
+ f = ((1,), (1,), (1,), (1,),)
+ libvlc_event_detach = p( ('libvlc_event_detach', dll), f )
+ libvlc_event_detach.__doc__ = """Unregister an event notification.
+@param p_event_manager: the event manager
+@param i_event_type: the desired event to which we want to unregister
+@param f_callback: the function to call when i_event_type occurs
+@param p_user_data: user provided data to carry with the event
+"""
+
+if hasattr(dll, 'libvlc_event_type_name'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_uint)
+ f = ((1,),)
+ libvlc_event_type_name = p( ('libvlc_event_type_name', dll), f )
+ libvlc_event_type_name.__doc__ = """Get an event's type name.
+@param event_type: the desired event
+"""
+
+if hasattr(dll, 'libvlc_get_log_verbosity'):
+ p = ctypes.CFUNCTYPE(ctypes.c_uint, Instance)
+ f = ((1,),)
+ libvlc_get_log_verbosity = p( ('libvlc_get_log_verbosity', dll), f )
+ libvlc_get_log_verbosity.__doc__ = """Return the VLC messaging verbosity level.
+@param p_instance: libvlc instance
+@return: verbosity level for messages
+"""
+
+if hasattr(dll, 'libvlc_set_log_verbosity'):
+ p = ctypes.CFUNCTYPE(None, Instance, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_set_log_verbosity = p( ('libvlc_set_log_verbosity', dll), f )
+ libvlc_set_log_verbosity.__doc__ = """Set the VLC messaging verbosity level.
+@param p_instance: libvlc log instance
+@param level: log level
+"""
+
+if hasattr(dll, 'libvlc_log_open'):
+ p = ctypes.CFUNCTYPE(Log, Instance)
+ f = ((1,),)
+ libvlc_log_open = p( ('libvlc_log_open', dll), f )
+ libvlc_log_open.__doc__ = """Open a VLC message log instance.
+@param p_instance: libvlc instance
+@return: log message instance or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_log_close'):
+ p = ctypes.CFUNCTYPE(None, Log)
+ f = ((1,),)
+ libvlc_log_close = p( ('libvlc_log_close', dll), f )
+ libvlc_log_close.__doc__ = """Close a VLC message log instance.
+@param p_log: libvlc log instance or NULL
+"""
+
+if hasattr(dll, 'libvlc_log_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_uint, Log)
+ f = ((1,),)
+ libvlc_log_count = p( ('libvlc_log_count', dll), f )
+ libvlc_log_count.__doc__ = """Returns the number of messages in a log instance.
+@param p_log: libvlc log instance or NULL
+@return: number of log messages, 0 if p_log is NULL
+"""
+
+if hasattr(dll, 'libvlc_log_clear'):
+ p = ctypes.CFUNCTYPE(None, Log)
+ f = ((1,),)
+ libvlc_log_clear = p( ('libvlc_log_clear', dll), f )
+ libvlc_log_clear.__doc__ = """Clear a log instance.
+All messages in the log are removed. The log should be cleared on a
+regular basis to avoid clogging.
+@param p_log: libvlc log instance or NULL
+"""
+
+if hasattr(dll, 'libvlc_log_get_iterator'):
+ p = ctypes.CFUNCTYPE(LogIterator, Log)
+ f = ((1,),)
+ libvlc_log_get_iterator = p( ('libvlc_log_get_iterator', dll), f )
+ libvlc_log_get_iterator.__doc__ = """Allocate and returns a new iterator to messages in log.
+@param p_log: libvlc log instance
+@return: log iterator object or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_log_iterator_free'):
+ p = ctypes.CFUNCTYPE(None, LogIterator)
+ f = ((1,),)
+ libvlc_log_iterator_free = p( ('libvlc_log_iterator_free', dll), f )
+ libvlc_log_iterator_free.__doc__ = """Release a previoulsy allocated iterator.
+@param p_iter: libvlc log iterator or NULL
+"""
+
+if hasattr(dll, 'libvlc_log_iterator_has_next'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, LogIterator)
+ f = ((1,),)
+ libvlc_log_iterator_has_next = p( ('libvlc_log_iterator_has_next', dll), f )
+ libvlc_log_iterator_has_next.__doc__ = """Return whether log iterator has more messages.
+@param p_iter: libvlc log iterator or NULL
+@return: true if iterator has more message objects, else false
+"""
+
+if hasattr(dll, 'libvlc_log_iterator_next'):
+ p = ctypes.CFUNCTYPE(ctypes.POINTER(LogMessage), LogIterator, ctypes.POINTER(LogMessage))
+ f = ((1,), (1,),)
+ libvlc_log_iterator_next = p( ('libvlc_log_iterator_next', dll), f )
+ libvlc_log_iterator_next.__doc__ = """Return the next log message.
+The message contents must not be freed
+@param p_iter: libvlc log iterator or NULL
+@param p_buffer: log buffer
+@return: log message object or NULL if none left
+"""
+
+if hasattr(dll, 'libvlc_media_new_location'):
+ p = ctypes.CFUNCTYPE(Media, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_media_new_location = p( ('libvlc_media_new_location', dll), f )
+ libvlc_media_new_location.__doc__ = """Create a media with a certain given media resource location.
+See libvlc_media_release
+@param p_instance: the instance
+@param psz_mrl: the MRL to read
+@return: the newly created media or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_media_new_path'):
+ p = ctypes.CFUNCTYPE(Media, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_media_new_path = p( ('libvlc_media_new_path', dll), f )
+ libvlc_media_new_path.__doc__ = """Create a media with a certain file path.
+See libvlc_media_release
+@param p_instance: the instance
+@param path: local filesystem path
+@return: the newly created media or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_media_new_as_node'):
+ p = ctypes.CFUNCTYPE(Media, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_media_new_as_node = p( ('libvlc_media_new_as_node', dll), f )
+ libvlc_media_new_as_node.__doc__ = """Create a media as an empty node with a given name.
+See libvlc_media_release
+@param p_instance: the instance
+@param psz_name: the name of the node
+@return: the new empty media or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_media_add_option'):
+ p = ctypes.CFUNCTYPE(None, Media, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_media_add_option = p( ('libvlc_media_add_option', dll), f )
+ libvlc_media_add_option.__doc__ = """Add an option to the media.
+This option will be used to determine how the media_player will
+read the media. This allows to use VLC's advanced
+reading/streaming options on a per-media basis.
+The options are detailed in vlc --long-help, for instance "--sout-all"
+@param p_md: the media descriptor
+@param ppsz_options: the options (as a string)
+"""
+
+if hasattr(dll, 'libvlc_media_add_option_flag'):
+ p = ctypes.CFUNCTYPE(None, Media, ctypes.c_char_p, ctypes.c_uint)
+ f = ((1,), (1,), (1,),)
+ libvlc_media_add_option_flag = p( ('libvlc_media_add_option_flag', dll), f )
+ libvlc_media_add_option_flag.__doc__ = """Add an option to the media with configurable flags.
+This option will be used to determine how the media_player will
+read the media. This allows to use VLC's advanced
+reading/streaming options on a per-media basis.
+The options are detailed in vlc --long-help, for instance "--sout-all"
+@param p_md: the media descriptor
+@param ppsz_options: the options (as a string)
+@param i_flags: the flags for this option
+"""
+
+if hasattr(dll, 'libvlc_media_retain'):
+ p = ctypes.CFUNCTYPE(None, Media)
+ f = ((1,),)
+ libvlc_media_retain = p( ('libvlc_media_retain', dll), f )
+ libvlc_media_retain.__doc__ = """Retain a reference to a media descriptor object (libvlc_media_t). Use
+libvlc_media_release() to decrement the reference count of a
+media descriptor object.
+@param p_md: the media descriptor
+"""
+
+if hasattr(dll, 'libvlc_media_release'):
+ p = ctypes.CFUNCTYPE(None, Media)
+ f = ((1,),)
+ libvlc_media_release = p( ('libvlc_media_release', dll), f )
+ libvlc_media_release.__doc__ = """Decrement the reference count of a media descriptor object. If the
+reference count is 0, then libvlc_media_release() will release the
+media descriptor object. It will send out an libvlc_MediaFreed event
+to all listeners. If the media descriptor object has been released it
+should not be used again.
+@param p_md: the media descriptor
+"""
+
+if hasattr(dll, 'libvlc_media_get_mrl'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, Media)
+ f = ((1,),)
+ libvlc_media_get_mrl = p( ('libvlc_media_get_mrl', dll), f )
+ libvlc_media_get_mrl.__doc__ = """Get the media resource locator (mrl) from a media descriptor object
+@param p_md: a media descriptor object
+@return: string with mrl of media descriptor object
+"""
+
+if hasattr(dll, 'libvlc_media_duplicate'):
+ p = ctypes.CFUNCTYPE(Media, Media)
+ f = ((1,),)
+ libvlc_media_duplicate = p( ('libvlc_media_duplicate', dll), f )
+ libvlc_media_duplicate.__doc__ = """Duplicate a media descriptor object.
+@param p_md: a media descriptor object.
+"""
+
+if hasattr(dll, 'libvlc_media_get_meta'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, Media, Meta)
+ f = ((1,), (1,),)
+ libvlc_media_get_meta = p( ('libvlc_media_get_meta', dll), f )
+ libvlc_media_get_meta.__doc__ = """Read the meta of the media.
+If the media has not yet been parsed this will return NULL.
+This methods automatically calls libvlc_media_parse_async(), so after calling
+it you may receive a libvlc_MediaMetaChanged event. If you prefer a synchronous
+version ensure that you call libvlc_media_parse() before get_meta().
+See libvlc_media_parse
+See libvlc_media_parse_async
+See libvlc_MediaMetaChanged
+@param p_md: the media descriptor
+@param e_meta: the meta to read
+@return: the media's meta
+"""
+
+if hasattr(dll, 'libvlc_media_set_meta'):
+ p = ctypes.CFUNCTYPE(None, Media, Meta, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_media_set_meta = p( ('libvlc_media_set_meta', dll), f )
+ libvlc_media_set_meta.__doc__ = """Set the meta of the media (this function will not save the meta, call
+libvlc_media_save_meta in order to save the meta)
+@param p_md: the media descriptor
+@param e_meta: the meta to write
+@param psz_value: the media's meta
+"""
+
+if hasattr(dll, 'libvlc_media_save_meta'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Media)
+ f = ((1,),)
+ libvlc_media_save_meta = p( ('libvlc_media_save_meta', dll), f )
+ libvlc_media_save_meta.__doc__ = """Save the meta previously set
+@param p_md: the media desriptor
+@return: true if the write operation was successfull
+"""
+
+if hasattr(dll, 'libvlc_media_get_state'):
+ p = ctypes.CFUNCTYPE(State, Media)
+ f = ((1,),)
+ libvlc_media_get_state = p( ('libvlc_media_get_state', dll), f )
+ libvlc_media_get_state.__doc__ = """Get current state of media descriptor object. Possible media states
+are defined in libvlc_structures.c ( libvlc_NothingSpecial=0,
+libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused,
+libvlc_Stopped, libvlc_Ended,
+libvlc_Error).
+See libvlc_state_t
+@param p_md: a media descriptor object
+@return: state of media descriptor object
+"""
+
+if hasattr(dll, 'libvlc_media_get_stats'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Media, ctypes.POINTER(MediaStats))
+ f = ((1,), (1,),)
+ libvlc_media_get_stats = p( ('libvlc_media_get_stats', dll), f )
+ libvlc_media_get_stats.__doc__ = """Get the current statistics about the media
+ (this structure must be allocated by the caller)
+@param p_md:: media descriptor object
+@param p_stats:: structure that contain the statistics about the media
+@return: true if the statistics are available, false otherwise
+"""
+
+if hasattr(dll, 'libvlc_media_subitems'):
+ p = ctypes.CFUNCTYPE(MediaList, Media)
+ f = ((1,),)
+ libvlc_media_subitems = p( ('libvlc_media_subitems', dll), f )
+ libvlc_media_subitems.__doc__ = """Get subitems of media descriptor object. This will increment
+the reference count of supplied media descriptor object. Use
+libvlc_media_list_release() to decrement the reference counting.
+and this is here for convenience */
+@param p_md: media descriptor object
+@return: list of media descriptor subitems or NULL
+"""
+
+if hasattr(dll, 'libvlc_media_event_manager'):
+ p = ctypes.CFUNCTYPE(EventManager, Media)
+ f = ((1,),)
+ libvlc_media_event_manager = p( ('libvlc_media_event_manager', dll), f )
+ libvlc_media_event_manager.__doc__ = """Get event manager from media descriptor object.
+NOTE: this function doesn't increment reference counting.
+@param p_md: a media descriptor object
+@return: event manager object
+"""
+
+if hasattr(dll, 'libvlc_media_get_duration'):
+ p = ctypes.CFUNCTYPE(ctypes.c_longlong, Media)
+ f = ((1,),)
+ libvlc_media_get_duration = p( ('libvlc_media_get_duration', dll), f )
+ libvlc_media_get_duration.__doc__ = """Get duration (in ms) of media descriptor object item.
+@param p_md: media descriptor object
+@return: duration of media item or -1 on error
+"""
+
+if hasattr(dll, 'libvlc_media_parse'):
+ p = ctypes.CFUNCTYPE(None, Media)
+ f = ((1,),)
+ libvlc_media_parse = p( ('libvlc_media_parse', dll), f )
+ libvlc_media_parse.__doc__ = """Parse a media.
+This fetches (local) meta data and tracks information.
+The method is synchronous.
+See libvlc_media_parse_async
+See libvlc_media_get_meta
+See libvlc_media_get_tracks_info
+@param p_md: media descriptor object
+"""
+
+if hasattr(dll, 'libvlc_media_parse_async'):
+ p = ctypes.CFUNCTYPE(None, Media)
+ f = ((1,),)
+ libvlc_media_parse_async = p( ('libvlc_media_parse_async', dll), f )
+ libvlc_media_parse_async.__doc__ = """Parse a media.
+This fetches (local) meta data and tracks information.
+The method is the asynchronous of libvlc_media_parse().
+To track when this is over you can listen to libvlc_MediaParsedChanged
+event. However if the media was already parsed you will not receive this
+event.
+See libvlc_media_parse
+See libvlc_MediaParsedChanged
+See libvlc_media_get_meta
+See libvlc_media_get_tracks_info
+@param p_md: media descriptor object
+"""
+
+if hasattr(dll, 'libvlc_media_is_parsed'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Media)
+ f = ((1,),)
+ libvlc_media_is_parsed = p( ('libvlc_media_is_parsed', dll), f )
+ libvlc_media_is_parsed.__doc__ = """Get Parsed status for media descriptor object.
+See libvlc_MediaParsedChanged
+@param p_md: media descriptor object
+@return: true if media object has been parsed otherwise it returns false
+"""
+
+if hasattr(dll, 'libvlc_media_set_user_data'):
+ p = ctypes.CFUNCTYPE(None, Media, ctypes.c_void_p)
+ f = ((1,), (1,),)
+ libvlc_media_set_user_data = p( ('libvlc_media_set_user_data', dll), f )
+ libvlc_media_set_user_data.__doc__ = """Sets media descriptor's user_data. user_data is specialized data
+accessed by the host application, VLC.framework uses it as a pointer to
+an native object that references a libvlc_media_t pointer
+@param p_md: media descriptor object
+@param p_new_user_data: pointer to user data
+"""
+
+if hasattr(dll, 'libvlc_media_get_user_data'):
+ p = ctypes.CFUNCTYPE(ctypes.c_void_p, Media)
+ f = ((1,),)
+ libvlc_media_get_user_data = p( ('libvlc_media_get_user_data', dll), f )
+ libvlc_media_get_user_data.__doc__ = """Get media descriptor's user_data. user_data is specialized data
+accessed by the host application, VLC.framework uses it as a pointer to
+an native object that references a libvlc_media_t pointer
+@param p_md: media descriptor object
+"""
+
+if hasattr(dll, 'libvlc_media_get_tracks_info'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Media, ctypes.POINTER(ctypes.POINTER(MediaTrackInfo)))
+ f = ((1,), (1,),)
+ libvlc_media_get_tracks_info = p( ('libvlc_media_get_tracks_info', dll), f )
+ libvlc_media_get_tracks_info.__doc__ = """Get media descriptor's elementary streams description
+Note, you need to play the media _one_ time with --sout="#description"
+Not doing this will result in an empty array, and doing it more than once
+will duplicate the entries in the array each time. Something like this:
+@begincode
+libvlc_media_player_t *player = libvlc_media_player_new_from_media(media);
+libvlc_media_add_option_flag(media, "sout=#description");
+libvlc_media_player_play(player);
+// ... wait until playing
+libvlc_media_player_release(player);
+@endcode
+This is very likely to change in next release, and be done at the parsing
+phase.
+descriptions (must be freed by the caller)
+return the number of Elementary Streams
+@param p_md: media descriptor object
+@param tracks: address to store an allocated array of Elementary Streams
+"""
+
+if hasattr(dll, 'libvlc_media_discoverer_new_from_name'):
+ p = ctypes.CFUNCTYPE(MediaDiscoverer, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_media_discoverer_new_from_name = p( ('libvlc_media_discoverer_new_from_name', dll), f )
+ libvlc_media_discoverer_new_from_name.__doc__ = """Discover media service by name.
+@param p_inst: libvlc instance
+@param psz_name: service name
+@return: media discover object or NULL in case of error
+"""
+
+if hasattr(dll, 'libvlc_media_discoverer_release'):
+ p = ctypes.CFUNCTYPE(None, MediaDiscoverer)
+ f = ((1,),)
+ libvlc_media_discoverer_release = p( ('libvlc_media_discoverer_release', dll), f )
+ libvlc_media_discoverer_release.__doc__ = """Release media discover object. If the reference count reaches 0, then
+the object will be released.
+@param p_mdis: media service discover object
+"""
+
+if hasattr(dll, 'libvlc_media_discoverer_localized_name'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, MediaDiscoverer)
+ f = ((1,),)
+ libvlc_media_discoverer_localized_name = p( ('libvlc_media_discoverer_localized_name', dll), f )
+ libvlc_media_discoverer_localized_name.__doc__ = """Get media service discover object its localized name.
+@param p_mdis: media discover object
+@return: localized name
+"""
+
+if hasattr(dll, 'libvlc_media_discoverer_media_list'):
+ p = ctypes.CFUNCTYPE(MediaList, MediaDiscoverer)
+ f = ((1,),)
+ libvlc_media_discoverer_media_list = p( ('libvlc_media_discoverer_media_list', dll), f )
+ libvlc_media_discoverer_media_list.__doc__ = """Get media service discover media list.
+@param p_mdis: media service discover object
+@return: list of media items
+"""
+
+if hasattr(dll, 'libvlc_media_discoverer_event_manager'):
+ p = ctypes.CFUNCTYPE(EventManager, MediaDiscoverer)
+ f = ((1,),)
+ libvlc_media_discoverer_event_manager = p( ('libvlc_media_discoverer_event_manager', dll), f )
+ libvlc_media_discoverer_event_manager.__doc__ = """Get event manager from media service discover object.
+@param p_mdis: media service discover object
+@return: event manager object.
+"""
+
+if hasattr(dll, 'libvlc_media_discoverer_is_running'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaDiscoverer)
+ f = ((1,),)
+ libvlc_media_discoverer_is_running = p( ('libvlc_media_discoverer_is_running', dll), f )
+ libvlc_media_discoverer_is_running.__doc__ = """Query if media service discover object is running.
+@param p_mdis: media service discover object
+@return: true if running, false if not
+"""
+
+if hasattr(dll, 'libvlc_media_library_new'):
+ p = ctypes.CFUNCTYPE(MediaLibrary, Instance)
+ f = ((1,),)
+ libvlc_media_library_new = p( ('libvlc_media_library_new', dll), f )
+ libvlc_media_library_new.__doc__ = """Create an new Media Library object
+@param p_instance: the libvlc instance
+@return: a new object or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_media_library_release'):
+ p = ctypes.CFUNCTYPE(None, MediaLibrary)
+ f = ((1,),)
+ libvlc_media_library_release = p( ('libvlc_media_library_release', dll), f )
+ libvlc_media_library_release.__doc__ = """Release media library object. This functions decrements the
+reference count of the media library object. If it reaches 0,
+then the object will be released.
+@param p_mlib: media library object
+"""
+
+if hasattr(dll, 'libvlc_media_library_retain'):
+ p = ctypes.CFUNCTYPE(None, MediaLibrary)
+ f = ((1,),)
+ libvlc_media_library_retain = p( ('libvlc_media_library_retain', dll), f )
+ libvlc_media_library_retain.__doc__ = """Retain a reference to a media library object. This function will
+increment the reference counting for this object. Use
+libvlc_media_library_release() to decrement the reference count.
+@param p_mlib: media library object
+"""
+
+if hasattr(dll, 'libvlc_media_library_load'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaLibrary)
+ f = ((1,),)
+ libvlc_media_library_load = p( ('libvlc_media_library_load', dll), f )
+ libvlc_media_library_load.__doc__ = """Load media library.
+@param p_mlib: media library object
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_media_library_media_list'):
+ p = ctypes.CFUNCTYPE(MediaList, MediaLibrary)
+ f = ((1,),)
+ libvlc_media_library_media_list = p( ('libvlc_media_library_media_list', dll), f )
+ libvlc_media_library_media_list.__doc__ = """Get media library subitems.
+@param p_mlib: media library object
+@return: media list subitems
+"""
+
+if hasattr(dll, 'libvlc_media_list_new'):
+ p = ctypes.CFUNCTYPE(MediaList, Instance)
+ f = ((1,),)
+ libvlc_media_list_new = p( ('libvlc_media_list_new', dll), f )
+ libvlc_media_list_new.__doc__ = """Create an empty media list.
+@param p_instance: libvlc instance
+@return: empty media list, or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_media_list_release'):
+ p = ctypes.CFUNCTYPE(None, MediaList)
+ f = ((1,),)
+ libvlc_media_list_release = p( ('libvlc_media_list_release', dll), f )
+ libvlc_media_list_release.__doc__ = """Release media list created with libvlc_media_list_new().
+@param p_ml: a media list created with libvlc_media_list_new()
+"""
+
+if hasattr(dll, 'libvlc_media_list_retain'):
+ p = ctypes.CFUNCTYPE(None, MediaList)
+ f = ((1,),)
+ libvlc_media_list_retain = p( ('libvlc_media_list_retain', dll), f )
+ libvlc_media_list_retain.__doc__ = """Retain reference to a media list
+@param p_ml: a media list created with libvlc_media_list_new()
+"""
+
+if hasattr(dll, 'libvlc_media_list_set_media'):
+ p = ctypes.CFUNCTYPE(None, MediaList, Media)
+ f = ((1,), (1,),)
+ libvlc_media_list_set_media = p( ('libvlc_media_list_set_media', dll), f )
+ libvlc_media_list_set_media.__doc__ = """Associate media instance with this media list instance.
+If another media instance was present it will be released.
+The libvlc_media_list_lock should NOT be held upon entering this function.
+@param p_ml: a media list instance
+@param p_md: media instance to add
+"""
+
+if hasattr(dll, 'libvlc_media_list_media'):
+ p = ctypes.CFUNCTYPE(Media, MediaList)
+ f = ((1,),)
+ libvlc_media_list_media = p( ('libvlc_media_list_media', dll), f )
+ libvlc_media_list_media.__doc__ = """Get media instance from this media list instance. This action will increase
+the refcount on the media instance.
+The libvlc_media_list_lock should NOT be held upon entering this function.
+@param p_ml: a media list instance
+@return: media instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_add_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaList, Media)
+ f = ((1,), (1,),)
+ libvlc_media_list_add_media = p( ('libvlc_media_list_add_media', dll), f )
+ libvlc_media_list_add_media.__doc__ = """Add media instance to media list
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_ml: a media list instance
+@param p_md: a media instance
+@return: 0 on success, -1 if the media list is read-only
+"""
+
+if hasattr(dll, 'libvlc_media_list_insert_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaList, Media, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_media_list_insert_media = p( ('libvlc_media_list_insert_media', dll), f )
+ libvlc_media_list_insert_media.__doc__ = """Insert media instance in media list on a position
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_ml: a media list instance
+@param p_md: a media instance
+@param i_pos: position in array where to insert
+@return: 0 on success, -1 if the media list si read-only
+"""
+
+if hasattr(dll, 'libvlc_media_list_remove_index'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaList, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_media_list_remove_index = p( ('libvlc_media_list_remove_index', dll), f )
+ libvlc_media_list_remove_index.__doc__ = """Remove media instance from media list on a position
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_ml: a media list instance
+@param i_pos: position in array where to insert
+@return: 0 on success, -1 if the list is read-only or the item was not found
+"""
+
+if hasattr(dll, 'libvlc_media_list_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaList)
+ f = ((1,),)
+ libvlc_media_list_count = p( ('libvlc_media_list_count', dll), f )
+ libvlc_media_list_count.__doc__ = """Get count on media list items
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_ml: a media list instance
+@return: number of items in media list
+"""
+
+if hasattr(dll, 'libvlc_media_list_item_at_index'):
+ p = ctypes.CFUNCTYPE(Media, MediaList, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_media_list_item_at_index = p( ('libvlc_media_list_item_at_index', dll), f )
+ libvlc_media_list_item_at_index.__doc__ = """List media instance in media list at a position
+The libvlc_media_list_lock should be held upon entering this function.
+In case of success, libvlc_media_retain() is called to increase the refcount
+on the media.
+@param p_ml: a media list instance
+@param i_pos: position in array where to insert
+@return: media instance at position i_pos, or NULL if not found.
+"""
+
+if hasattr(dll, 'libvlc_media_list_index_of_item'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaList, Media)
+ f = ((1,), (1,),)
+ libvlc_media_list_index_of_item = p( ('libvlc_media_list_index_of_item', dll), f )
+ libvlc_media_list_index_of_item.__doc__ = """Find index position of List media instance in media list.
+Warning: the function will return the first matched position.
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_ml: a media list instance
+@param p_md: media list instance
+@return: position of media instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_is_readonly'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaList)
+ f = ((1,),)
+ libvlc_media_list_is_readonly = p( ('libvlc_media_list_is_readonly', dll), f )
+ libvlc_media_list_is_readonly.__doc__ = """This indicates if this media list is read-only from a user point of view
+@param p_ml: media list instance
+@return: 0 on readonly, 1 on readwrite
+"""
+
+if hasattr(dll, 'libvlc_media_list_lock'):
+ p = ctypes.CFUNCTYPE(None, MediaList)
+ f = ((1,),)
+ libvlc_media_list_lock = p( ('libvlc_media_list_lock', dll), f )
+ libvlc_media_list_lock.__doc__ = """Get lock on media list items
+@param p_ml: a media list instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_unlock'):
+ p = ctypes.CFUNCTYPE(None, MediaList)
+ f = ((1,),)
+ libvlc_media_list_unlock = p( ('libvlc_media_list_unlock', dll), f )
+ libvlc_media_list_unlock.__doc__ = """Release lock on media list items
+The libvlc_media_list_lock should be held upon entering this function.
+@param p_ml: a media list instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_event_manager'):
+ p = ctypes.CFUNCTYPE(EventManager, MediaList)
+ f = ((1,),)
+ libvlc_media_list_event_manager = p( ('libvlc_media_list_event_manager', dll), f )
+ libvlc_media_list_event_manager.__doc__ = """Get libvlc_event_manager from this media list instance.
+The p_event_manager is immutable, so you don't have to hold the lock
+@param p_ml: a media list instance
+@return: libvlc_event_manager
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_new'):
+ p = ctypes.CFUNCTYPE(MediaListPlayer, Instance)
+ f = ((1,),)
+ libvlc_media_list_player_new = p( ('libvlc_media_list_player_new', dll), f )
+ libvlc_media_list_player_new.__doc__ = """Create new media_list_player.
+@param p_instance: libvlc instance
+@return: media list player instance or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_release'):
+ p = ctypes.CFUNCTYPE(None, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_release = p( ('libvlc_media_list_player_release', dll), f )
+ libvlc_media_list_player_release.__doc__ = """Release media_list_player.
+@param p_mlp: media list player instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_event_manager'):
+ p = ctypes.CFUNCTYPE(EventManager, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_event_manager = p( ('libvlc_media_list_player_event_manager', dll), f )
+ libvlc_media_list_player_event_manager.__doc__ = """Return the event manager of this media_list_player.
+@param p_mlp: media list player instance
+@return: the event manager
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_set_media_player'):
+ p = ctypes.CFUNCTYPE(None, MediaListPlayer, MediaPlayer)
+ f = ((1,), (1,),)
+ libvlc_media_list_player_set_media_player = p( ('libvlc_media_list_player_set_media_player', dll), f )
+ libvlc_media_list_player_set_media_player.__doc__ = """Replace media player in media_list_player with this instance.
+@param p_mlp: media list player instance
+@param p_mi: media player instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_set_media_list'):
+ p = ctypes.CFUNCTYPE(None, MediaListPlayer, MediaList)
+ f = ((1,), (1,),)
+ libvlc_media_list_player_set_media_list = p( ('libvlc_media_list_player_set_media_list', dll), f )
+ libvlc_media_list_player_set_media_list.__doc__ = """Set the media list associated with the player
+@param p_mlp: media list player instance
+@param p_mlist: list of media
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_play'):
+ p = ctypes.CFUNCTYPE(None, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_play = p( ('libvlc_media_list_player_play', dll), f )
+ libvlc_media_list_player_play.__doc__ = """Play media list
+@param p_mlp: media list player instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_pause'):
+ p = ctypes.CFUNCTYPE(None, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_pause = p( ('libvlc_media_list_player_pause', dll), f )
+ libvlc_media_list_player_pause.__doc__ = """Pause media list
+@param p_mlp: media list player instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_is_playing'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_is_playing = p( ('libvlc_media_list_player_is_playing', dll), f )
+ libvlc_media_list_player_is_playing.__doc__ = """Is media list playing?
+@param p_mlp: media list player instance
+@return: true for playing and false for not playing
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_get_state'):
+ p = ctypes.CFUNCTYPE(State, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_get_state = p( ('libvlc_media_list_player_get_state', dll), f )
+ libvlc_media_list_player_get_state.__doc__ = """Get current libvlc_state of media list player
+@param p_mlp: media list player instance
+@return: libvlc_state_t for media list player
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_play_item_at_index'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaListPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_media_list_player_play_item_at_index = p( ('libvlc_media_list_player_play_item_at_index', dll), f )
+ libvlc_media_list_player_play_item_at_index.__doc__ = """Play media list item at position index
+@param p_mlp: media list player instance
+@param i_index: index in media list to play
+@return: 0 upon success -1 if the item wasn't found
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_play_item'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaListPlayer, Media)
+ f = ((1,), (1,),)
+ libvlc_media_list_player_play_item = p( ('libvlc_media_list_player_play_item', dll), f )
+ libvlc_media_list_player_play_item.__doc__ = """Play the given media item
+@param p_mlp: media list player instance
+@param p_md: the media instance
+@return: 0 upon success, -1 if the media is not part of the media list
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_stop'):
+ p = ctypes.CFUNCTYPE(None, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_stop = p( ('libvlc_media_list_player_stop', dll), f )
+ libvlc_media_list_player_stop.__doc__ = """Stop playing media list
+@param p_mlp: media list player instance
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_next'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_next = p( ('libvlc_media_list_player_next', dll), f )
+ libvlc_media_list_player_next.__doc__ = """Play next item from media list
+@param p_mlp: media list player instance
+@return: 0 upon success -1 if there is no next item
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_previous'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaListPlayer)
+ f = ((1,),)
+ libvlc_media_list_player_previous = p( ('libvlc_media_list_player_previous', dll), f )
+ libvlc_media_list_player_previous.__doc__ = """Play previous item from media list
+@param p_mlp: media list player instance
+@return: 0 upon success -1 if there is no previous item
+"""
+
+if hasattr(dll, 'libvlc_media_list_player_set_playback_mode'):
+ p = ctypes.CFUNCTYPE(None, MediaListPlayer, PlaybackMode)
+ f = ((1,), (1,),)
+ libvlc_media_list_player_set_playback_mode = p( ('libvlc_media_list_player_set_playback_mode', dll), f )
+ libvlc_media_list_player_set_playback_mode.__doc__ = """Sets the playback mode for the playlist
+@param p_mlp: media list player instance
+@param e_mode: playback mode specification
+"""
+
+if hasattr(dll, 'libvlc_media_player_new'):
+ p = ctypes.CFUNCTYPE(MediaPlayer, Instance)
+ f = ((1,),)
+ libvlc_media_player_new = p( ('libvlc_media_player_new', dll), f )
+ libvlc_media_player_new.__doc__ = """Create an empty Media Player object
+ should be created.
+@param p_libvlc_instance: the libvlc instance in which the Media Player
+@return: a new media player object, or NULL on error.
+"""
+
+if hasattr(dll, 'libvlc_media_player_new_from_media'):
+ p = ctypes.CFUNCTYPE(MediaPlayer, Media)
+ f = ((1,),)
+ libvlc_media_player_new_from_media = p( ('libvlc_media_player_new_from_media', dll), f )
+ libvlc_media_player_new_from_media.__doc__ = """Create a Media Player object from a Media
+ destroyed.
+@param p_md: the media. Afterwards the p_md can be safely
+@return: a new media player object, or NULL on error.
+"""
+
+if hasattr(dll, 'libvlc_media_player_release'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_release = p( ('libvlc_media_player_release', dll), f )
+ libvlc_media_player_release.__doc__ = """Release a media_player after use
+Decrement the reference count of a media player object. If the
+reference count is 0, then libvlc_media_player_release() will
+release the media player object. If the media player object
+has been released, then it should not be used again.
+@param p_mi: the Media Player to free
+"""
+
+if hasattr(dll, 'libvlc_media_player_retain'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_retain = p( ('libvlc_media_player_retain', dll), f )
+ libvlc_media_player_retain.__doc__ = """Retain a reference to a media player object. Use
+libvlc_media_player_release() to decrement reference count.
+@param p_mi: media player object
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_media'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, Media)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_media = p( ('libvlc_media_player_set_media', dll), f )
+ libvlc_media_player_set_media.__doc__ = """Set the media that will be used by the media_player. If any,
+previous md will be released.
+ destroyed.
+@param p_mi: the Media Player
+@param p_md: the Media. Afterwards the p_md can be safely
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_media'):
+ p = ctypes.CFUNCTYPE(Media, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_media = p( ('libvlc_media_player_get_media', dll), f )
+ libvlc_media_player_get_media.__doc__ = """Get the media used by the media_player.
+ media is associated
+@param p_mi: the Media Player
+@return: the media associated with p_mi, or NULL if no
+"""
+
+if hasattr(dll, 'libvlc_media_player_event_manager'):
+ p = ctypes.CFUNCTYPE(EventManager, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_event_manager = p( ('libvlc_media_player_event_manager', dll), f )
+ libvlc_media_player_event_manager.__doc__ = """Get the Event Manager from which the media player send event.
+@param p_mi: the Media Player
+@return: the event manager associated with p_mi
+"""
+
+if hasattr(dll, 'libvlc_media_player_is_playing'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_is_playing = p( ('libvlc_media_player_is_playing', dll), f )
+ libvlc_media_player_is_playing.__doc__ = """is_playing
+@param p_mi: the Media Player
+@return: 1 if the media player is playing, 0 otherwise
+"""
+
+if hasattr(dll, 'libvlc_media_player_play'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_play = p( ('libvlc_media_player_play', dll), f )
+ libvlc_media_player_play.__doc__ = """Play
+@param p_mi: the Media Player
+@return: 0 if playback started (and was already started), or -1 on error.
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_pause'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_pause = p( ('libvlc_media_player_set_pause', dll), f )
+ libvlc_media_player_set_pause.__doc__ = """Pause or resume (no effect if there is no media)
+@version: LibVLC 1.1.1 or later
+@param mp: the Media Player
+@param do_pause: play/resume if zero, pause if non-zero
+"""
+
+if hasattr(dll, 'libvlc_media_player_pause'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_pause = p( ('libvlc_media_player_pause', dll), f )
+ libvlc_media_player_pause.__doc__ = """Toggle pause (no effect if there is no media)
+@param p_mi: the Media Player
+"""
+
+if hasattr(dll, 'libvlc_media_player_stop'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_stop = p( ('libvlc_media_player_stop', dll), f )
+ libvlc_media_player_stop.__doc__ = """Stop (no effect if there is no media)
+@param p_mi: the Media Player
+"""
+
+if hasattr(dll, 'libvlc_video_set_format'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint)
+ f = ((1,), (1,), (1,), (1,), (1,),)
+ libvlc_video_set_format = p( ('libvlc_video_set_format', dll), f )
+ libvlc_video_set_format.__doc__ = """Set decoded video chroma and dimensions. This only works in combination with
+libvlc_video_set_callbacks().
+ (e.g. "RV32" or "I420")
+@version: LibVLC 1.1.1 or later
+@param mp: the media player
+@param chroma: a four-characters string identifying the chroma
+@param width: pixel width
+@param height: pixel height
+@param pitch: line pitch (in bytes)
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_nsobject'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_void_p)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_nsobject = p( ('libvlc_media_player_set_nsobject', dll), f )
+ libvlc_media_player_set_nsobject.__doc__ = """Set the NSView handler where the media player should render its video output.
+Use the vout called "macosx".
+The drawable is an NSObject that follow the VLCOpenGLVideoViewEmbedding
+protocol:
+@begincode
+\@protocol VLCOpenGLVideoViewEmbedding <NSObject>
+- (void)addVoutSubview:(NSView *)view;
+- (void)removeVoutSubview:(NSView *)view;
+\@end
+@endcode
+Or it can be an NSView object.
+If you want to use it along with Qt4 see the QMacCocoaViewContainer. Then
+the following code should work:
+@begincode
+{
+ NSView *video = [[NSView alloc] init];
+ QMacCocoaViewContainer *container = new QMacCocoaViewContainer(video, parent);
+ libvlc_media_player_set_nsobject(mp, video);
+ [video release];
+}
+@endcode
+You can find a live example in VLCVideoView in VLCKit.framework.
+the VLCOpenGLVideoViewEmbedding protocol.
+@param p_mi: the Media Player
+@param drawable: the drawable that is either an NSView or an object following
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_nsobject'):
+ p = ctypes.CFUNCTYPE(ctypes.c_void_p, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_nsobject = p( ('libvlc_media_player_get_nsobject', dll), f )
+ libvlc_media_player_get_nsobject.__doc__ = """Get the NSView handler previously set with libvlc_media_player_set_nsobject().
+@param p_mi: the Media Player
+@return: the NSView handler or 0 if none where set
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_agl'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint32)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_agl = p( ('libvlc_media_player_set_agl', dll), f )
+ libvlc_media_player_set_agl.__doc__ = """Set the agl handler where the media player should render its video output.
+@param p_mi: the Media Player
+@param drawable: the agl handler
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_agl'):
+ p = ctypes.CFUNCTYPE(ctypes.c_uint32, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_agl = p( ('libvlc_media_player_get_agl', dll), f )
+ libvlc_media_player_get_agl.__doc__ = """Get the agl handler previously set with libvlc_media_player_set_agl().
+@param p_mi: the Media Player
+@return: the agl handler or 0 if none where set
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_xwindow'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint32)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_xwindow = p( ('libvlc_media_player_set_xwindow', dll), f )
+ libvlc_media_player_set_xwindow.__doc__ = """Set an X Window System drawable where the media player should render its
+video output. If LibVLC was built without X11 output support, then this has
+no effects.
+The specified identifier must correspond to an existing Input/Output class
+X11 window. Pixmaps are <b>not</b> supported. The caller shall ensure that
+the X11 server is the same as the one the VLC instance has been configured
+with.
+@param p_mi: the Media Player
+@param drawable: the ID of the X window
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_xwindow'):
+ p = ctypes.CFUNCTYPE(ctypes.c_uint32, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_xwindow = p( ('libvlc_media_player_get_xwindow', dll), f )
+ libvlc_media_player_get_xwindow.__doc__ = """Get the X Window System window identifier previously set with
+libvlc_media_player_set_xwindow(). Note that this will return the identifier
+even if VLC is not currently using it (for instance if it is playing an
+audio-only input).
+@param p_mi: the Media Player
+@return: an X window ID, or 0 if none where set.
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_hwnd'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_void_p)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_hwnd = p( ('libvlc_media_player_set_hwnd', dll), f )
+ libvlc_media_player_set_hwnd.__doc__ = """Set a Win32/Win64 API window handle (HWND) where the media player should
+render its video output. If LibVLC was built without Win32/Win64 API output
+support, then this has no effects.
+@param p_mi: the Media Player
+@param drawable: windows handle of the drawable
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_hwnd'):
+ p = ctypes.CFUNCTYPE(ctypes.c_void_p, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_hwnd = p( ('libvlc_media_player_get_hwnd', dll), f )
+ libvlc_media_player_get_hwnd.__doc__ = """Get the Windows API window handle (HWND) previously set with
+libvlc_media_player_set_hwnd(). The handle will be returned even if LibVLC
+is not currently outputting any video to it.
+@param p_mi: the Media Player
+@return: a window handle or NULL if there are none.
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_length'):
+ p = ctypes.CFUNCTYPE(ctypes.c_longlong, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_length = p( ('libvlc_media_player_get_length', dll), f )
+ libvlc_media_player_get_length.__doc__ = """Get the current movie length (in ms).
+@param p_mi: the Media Player
+@return: the movie length (in ms), or -1 if there is no media.
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_time'):
+ p = ctypes.CFUNCTYPE(ctypes.c_longlong, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_time = p( ('libvlc_media_player_get_time', dll), f )
+ libvlc_media_player_get_time.__doc__ = """Get the current movie time (in ms).
+@param p_mi: the Media Player
+@return: the movie time (in ms), or -1 if there is no media.
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_time'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_longlong)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_time = p( ('libvlc_media_player_set_time', dll), f )
+ libvlc_media_player_set_time.__doc__ = """Set the movie time (in ms). This has no effect if no media is being played.
+Not all formats and protocols support this.
+@param p_mi: the Media Player
+@param i_time: the movie time (in ms).
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_position'):
+ p = ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_position = p( ('libvlc_media_player_get_position', dll), f )
+ libvlc_media_player_get_position.__doc__ = """Get movie position.
+@param p_mi: the Media Player
+@return: movie position, or -1. in case of error
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_position'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_float)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_position = p( ('libvlc_media_player_set_position', dll), f )
+ libvlc_media_player_set_position.__doc__ = """Set movie position. This has no effect if playback is not enabled.
+This might not work depending on the underlying input format and protocol.
+@param p_mi: the Media Player
+@param f_pos: the position
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_chapter'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_chapter = p( ('libvlc_media_player_set_chapter', dll), f )
+ libvlc_media_player_set_chapter.__doc__ = """Set movie chapter (if applicable).
+@param p_mi: the Media Player
+@param i_chapter: chapter number to play
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_chapter'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_chapter = p( ('libvlc_media_player_get_chapter', dll), f )
+ libvlc_media_player_get_chapter.__doc__ = """Get movie chapter.
+@param p_mi: the Media Player
+@return: chapter number currently playing, or -1 if there is no media.
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_chapter_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_chapter_count = p( ('libvlc_media_player_get_chapter_count', dll), f )
+ libvlc_media_player_get_chapter_count.__doc__ = """Get movie chapter count
+@param p_mi: the Media Player
+@return: number of chapters in movie, or -1.
+"""
+
+if hasattr(dll, 'libvlc_media_player_will_play'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_will_play = p( ('libvlc_media_player_will_play', dll), f )
+ libvlc_media_player_will_play.__doc__ = """Is the player able to play
+@param p_mi: the Media Player
+@return: boolean
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_chapter_count_for_title'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_media_player_get_chapter_count_for_title = p( ('libvlc_media_player_get_chapter_count_for_title', dll), f )
+ libvlc_media_player_get_chapter_count_for_title.__doc__ = """Get title chapter count
+@param p_mi: the Media Player
+@param i_title: title
+@return: number of chapters in title, or -1
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_title'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_title = p( ('libvlc_media_player_set_title', dll), f )
+ libvlc_media_player_set_title.__doc__ = """Set movie title
+@param p_mi: the Media Player
+@param i_title: title number to play
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_title'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_title = p( ('libvlc_media_player_get_title', dll), f )
+ libvlc_media_player_get_title.__doc__ = """Get movie title
+@param p_mi: the Media Player
+@return: title number currently playing, or -1
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_title_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_title_count = p( ('libvlc_media_player_get_title_count', dll), f )
+ libvlc_media_player_get_title_count.__doc__ = """Get movie title count
+@param p_mi: the Media Player
+@return: title number count, or -1
+"""
+
+if hasattr(dll, 'libvlc_media_player_previous_chapter'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_previous_chapter = p( ('libvlc_media_player_previous_chapter', dll), f )
+ libvlc_media_player_previous_chapter.__doc__ = """Set previous chapter (if applicable)
+@param p_mi: the Media Player
+"""
+
+if hasattr(dll, 'libvlc_media_player_next_chapter'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_next_chapter = p( ('libvlc_media_player_next_chapter', dll), f )
+ libvlc_media_player_next_chapter.__doc__ = """Set next chapter (if applicable)
+@param p_mi: the Media Player
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_rate'):
+ p = ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_rate = p( ('libvlc_media_player_get_rate', dll), f )
+ libvlc_media_player_get_rate.__doc__ = """Get the requested movie play rate.
+@warning Depending on the underlying media, the requested rate may be
+different from the real playback rate.
+@param p_mi: the Media Player
+@return: movie play rate
+"""
+
+if hasattr(dll, 'libvlc_media_player_set_rate'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_float)
+ f = ((1,), (1,),)
+ libvlc_media_player_set_rate = p( ('libvlc_media_player_set_rate', dll), f )
+ libvlc_media_player_set_rate.__doc__ = """Set movie play rate
+not actually work depending on the underlying media protocol)
+@param p_mi: the Media Player
+@param rate: movie play rate to set
+@return: -1 if an error was detected, 0 otherwise (but even then, it might
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_state'):
+ p = ctypes.CFUNCTYPE(State, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_state = p( ('libvlc_media_player_get_state', dll), f )
+ libvlc_media_player_get_state.__doc__ = """Get current movie state
+@param p_mi: the Media Player
+@return: the current state of the media player (playing, paused, ...) See libvlc_state_t
+"""
+
+if hasattr(dll, 'libvlc_media_player_get_fps'):
+ p = ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_get_fps = p( ('libvlc_media_player_get_fps', dll), f )
+ libvlc_media_player_get_fps.__doc__ = """Get movie fps rate
+@param p_mi: the Media Player
+@return: frames per second (fps) for this playing movie, or 0 if unspecified
+"""
+
+if hasattr(dll, 'libvlc_media_player_has_vout'):
+ p = ctypes.CFUNCTYPE(ctypes.c_uint, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_has_vout = p( ('libvlc_media_player_has_vout', dll), f )
+ libvlc_media_player_has_vout.__doc__ = """How many video outputs does this media player have?
+@param p_mi: the media player
+@return: the number of video outputs
+"""
+
+if hasattr(dll, 'libvlc_media_player_is_seekable'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_is_seekable = p( ('libvlc_media_player_is_seekable', dll), f )
+ libvlc_media_player_is_seekable.__doc__ = """Is this media player seekable?
+@param p_mi: the media player
+@return: true if the media player can seek
+"""
+
+if hasattr(dll, 'libvlc_media_player_can_pause'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_can_pause = p( ('libvlc_media_player_can_pause', dll), f )
+ libvlc_media_player_can_pause.__doc__ = """Can this media player be paused?
+@param p_mi: the media player
+@return: true if the media player can pause
+"""
+
+if hasattr(dll, 'libvlc_media_player_next_frame'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_media_player_next_frame = p( ('libvlc_media_player_next_frame', dll), f )
+ libvlc_media_player_next_frame.__doc__ = """Display the next frame (if supported)
+@param p_mi: the media player
+"""
+
+if hasattr(dll, 'libvlc_media_player_navigate'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_media_player_navigate = p( ('libvlc_media_player_navigate', dll), f )
+ libvlc_media_player_navigate.__doc__ = """Navigate through DVD Menu
+@version: libVLC 1.2.0 or later
+@param p_mi: the Media Player
+@param navigate: the Navigation mode
+"""
+
+if hasattr(dll, 'libvlc_track_description_release'):
+ p = ctypes.CFUNCTYPE(None, ctypes.POINTER(TrackDescription))
+ f = ((1,),)
+ libvlc_track_description_release = p( ('libvlc_track_description_release', dll), f )
+ libvlc_track_description_release.__doc__ = """Release (free) libvlc_track_description_t
+@param p_track_description: the structure to release
+"""
+
+if hasattr(dll, 'libvlc_toggle_fullscreen'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_toggle_fullscreen = p( ('libvlc_toggle_fullscreen', dll), f )
+ libvlc_toggle_fullscreen.__doc__ = """Toggle fullscreen status on non-embedded video outputs.
+@warning The same limitations applies to this function
+as to libvlc_set_fullscreen().
+@param p_mi: the media player
+"""
+
+if hasattr(dll, 'libvlc_set_fullscreen'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_set_fullscreen = p( ('libvlc_set_fullscreen', dll), f )
+ libvlc_set_fullscreen.__doc__ = """Enable or disable fullscreen.
+@warning With most window managers, only a top-level windows can be in
+full-screen mode. Hence, this function will not operate properly if
+libvlc_media_player_set_xwindow() was used to embed the video in a
+non-top-level window. In that case, the embedding window must be reparented
+to the root window <b>before</b> fullscreen mode is enabled. You will want
+to reparent it back to its normal parent when disabling fullscreen.
+@param p_mi: the media player
+@param b_fullscreen: boolean for fullscreen status
+"""
+
+if hasattr(dll, 'libvlc_get_fullscreen'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_get_fullscreen = p( ('libvlc_get_fullscreen', dll), f )
+ libvlc_get_fullscreen.__doc__ = """Get current fullscreen status.
+@param p_mi: the media player
+@return: the fullscreen status (boolean)
+"""
+
+if hasattr(dll, 'libvlc_video_set_key_input'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_set_key_input = p( ('libvlc_video_set_key_input', dll), f )
+ libvlc_video_set_key_input.__doc__ = """Enable or disable key press events handling, according to the LibVLC hotkeys
+configuration. By default and for historical reasons, keyboard events are
+handled by the LibVLC video widget.
+@note: On X11, there can be only one subscriber for key press and mouse
+click events per window. If your application has subscribed to those events
+for the X window ID of the video widget, then LibVLC will not be able to
+handle key presses and mouse clicks in any case.
+@warning: This function is only implemented for X11 and Win32 at the moment.
+@param p_mi: the media player
+@param on: true to handle key press events, false to ignore them.
+"""
+
+if hasattr(dll, 'libvlc_video_set_mouse_input'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_set_mouse_input = p( ('libvlc_video_set_mouse_input', dll), f )
+ libvlc_video_set_mouse_input.__doc__ = """Enable or disable mouse click events handling. By default, those events are
+handled. This is needed for DVD menus to work, as well as a few video
+filters such as "puzzle".
+@note: See also libvlc_video_set_key_input().
+@warning: This function is only implemented for X11 and Win32 at the moment.
+@param p_mi: the media player
+@param on: true to handle mouse click events, false to ignore them.
+"""
+
+if hasattr(dll, 'libvlc_video_get_size'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint))
+ f = ((1,), (1,), (2,), (2,),)
+ libvlc_video_get_size = p( ('libvlc_video_get_size', dll), f )
+ libvlc_video_get_size.__doc__ = """Get the pixel dimensions of a video.
+@param p_mi: media player
+@param num: number of the video (starting from, and most commonly 0)
+@return x, y
+"""
+
+if hasattr(dll, 'libvlc_video_get_cursor'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
+ f = ((1,), (1,), (2,), (2,),)
+ libvlc_video_get_cursor = p( ('libvlc_video_get_cursor', dll), f )
+ libvlc_video_get_cursor.__doc__ = """Get the mouse pointer coordinates over a video.
+Coordinates are expressed in terms of the decoded video resolution,
+<b>not</b> in terms of pixels on the screen/viewport (to get the latter,
+you can query your windowing system directly).
+Either of the coordinates may be negative or larger than the corresponding
+dimension of the video, if the cursor is outside the rendering area.
+@warning The coordinates may be out-of-date if the pointer is not located
+on the video rendering area. LibVLC does not track the pointer if it is
+outside of the video widget.
+@note LibVLC does not support multiple pointers (it does of course support
+multiple input devices sharing the same pointer) at the moment.
+@param p_mi: media player
+@param num: number of the video (starting from, and most commonly 0)
+@return x, y
+"""
+
+if hasattr(dll, 'libvlc_video_get_scale'):
+ p = ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_scale = p( ('libvlc_video_get_scale', dll), f )
+ libvlc_video_get_scale.__doc__ = """Get the current video scaling factor.
+See also libvlc_video_set_scale().
+to fit to the output window/drawable automatically.
+@param p_mi: the media player
+@return: the currently configured zoom factor, or 0. if the video is set
+"""
+
+if hasattr(dll, 'libvlc_video_set_scale'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_float)
+ f = ((1,), (1,),)
+ libvlc_video_set_scale = p( ('libvlc_video_set_scale', dll), f )
+ libvlc_video_set_scale.__doc__ = """Set the video scaling factor. That is the ratio of the number of pixels on
+screen to the number of pixels in the original decoded video in each
+dimension. Zero is a special value; it will adjust the video to the output
+window/drawable (in windowed mode) or the entire screen.
+Note that not all video outputs support scaling.
+@param p_mi: the media player
+@param f_factor: the scaling factor, or zero
+"""
+
+if hasattr(dll, 'libvlc_video_get_aspect_ratio'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_aspect_ratio = p( ('libvlc_video_get_aspect_ratio', dll), f )
+ libvlc_video_get_aspect_ratio.__doc__ = """Get current video aspect ratio.
+(the result must be released with free() or libvlc_free()).
+@param p_mi: the media player
+@return: the video aspect ratio or NULL if unspecified
+"""
+
+if hasattr(dll, 'libvlc_video_set_aspect_ratio'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_video_set_aspect_ratio = p( ('libvlc_video_set_aspect_ratio', dll), f )
+ libvlc_video_set_aspect_ratio.__doc__ = """Set new video aspect ratio.
+@note: Invalid aspect ratios are ignored.
+@param p_mi: the media player
+@param psz_aspect: new video aspect-ratio or NULL to reset to default
+"""
+
+if hasattr(dll, 'libvlc_video_get_spu'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_spu = p( ('libvlc_video_get_spu', dll), f )
+ libvlc_video_get_spu.__doc__ = """Get current video subtitle.
+@param p_mi: the media player
+@return: the video subtitle selected, or -1 if none
+"""
+
+if hasattr(dll, 'libvlc_video_get_spu_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_spu_count = p( ('libvlc_video_get_spu_count', dll), f )
+ libvlc_video_get_spu_count.__doc__ = """Get the number of available video subtitles.
+@param p_mi: the media player
+@return: the number of available video subtitles
+"""
+
+if hasattr(dll, 'libvlc_video_get_spu_description'):
+ p = ctypes.CFUNCTYPE(ctypes.POINTER(TrackDescription), MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_spu_description = p( ('libvlc_video_get_spu_description', dll), f )
+ libvlc_video_get_spu_description.__doc__ = """Get the description of available video subtitles.
+@param p_mi: the media player
+@return: list containing description of available video subtitles
+"""
+
+if hasattr(dll, 'libvlc_video_set_spu'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_set_spu = p( ('libvlc_video_set_spu', dll), f )
+ libvlc_video_set_spu.__doc__ = """Set new video subtitle.
+@param p_mi: the media player
+@param i_spu: new video subtitle to select
+@return: 0 on success, -1 if out of range
+"""
+
+if hasattr(dll, 'libvlc_video_set_subtitle_file'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_video_set_subtitle_file = p( ('libvlc_video_set_subtitle_file', dll), f )
+ libvlc_video_set_subtitle_file.__doc__ = """Set new video subtitle file.
+@param p_mi: the media player
+@param psz_subtitle: new video subtitle file
+@return: the success status (boolean)
+"""
+
+if hasattr(dll, 'libvlc_video_get_title_description'):
+ p = ctypes.CFUNCTYPE(ctypes.POINTER(TrackDescription), MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_title_description = p( ('libvlc_video_get_title_description', dll), f )
+ libvlc_video_get_title_description.__doc__ = """Get the description of available titles.
+@param p_mi: the media player
+@return: list containing description of available titles
+"""
+
+if hasattr(dll, 'libvlc_video_get_chapter_description'):
+ p = ctypes.CFUNCTYPE(ctypes.POINTER(TrackDescription), MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_video_get_chapter_description = p( ('libvlc_video_get_chapter_description', dll), f )
+ libvlc_video_get_chapter_description.__doc__ = """Get the description of available chapters for specific title.
+@param p_mi: the media player
+@param i_title: selected title
+@return: list containing description of available chapter for title i_title
+"""
+
+if hasattr(dll, 'libvlc_video_get_crop_geometry'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_crop_geometry = p( ('libvlc_video_get_crop_geometry', dll), f )
+ libvlc_video_get_crop_geometry.__doc__ = """Get current crop filter geometry.
+@param p_mi: the media player
+@return: the crop filter geometry or NULL if unset
+"""
+
+if hasattr(dll, 'libvlc_video_set_crop_geometry'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_video_set_crop_geometry = p( ('libvlc_video_set_crop_geometry', dll), f )
+ libvlc_video_set_crop_geometry.__doc__ = """Set new crop filter geometry.
+@param p_mi: the media player
+@param psz_geometry: new crop filter geometry (NULL to unset)
+"""
+
+if hasattr(dll, 'libvlc_video_get_teletext'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_teletext = p( ('libvlc_video_get_teletext', dll), f )
+ libvlc_video_get_teletext.__doc__ = """Get current teletext page requested.
+@param p_mi: the media player
+@return: the current teletext page requested.
+"""
+
+if hasattr(dll, 'libvlc_video_set_teletext'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_video_set_teletext = p( ('libvlc_video_set_teletext', dll), f )
+ libvlc_video_set_teletext.__doc__ = """Set new teletext page to retrieve.
+@param p_mi: the media player
+@param i_page: teletex page number requested
+"""
+
+if hasattr(dll, 'libvlc_toggle_teletext'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_toggle_teletext = p( ('libvlc_toggle_teletext', dll), f )
+ libvlc_toggle_teletext.__doc__ = """Toggle teletext transparent status on video output.
+@param p_mi: the media player
+"""
+
+if hasattr(dll, 'libvlc_video_get_track_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_track_count = p( ('libvlc_video_get_track_count', dll), f )
+ libvlc_video_get_track_count.__doc__ = """Get number of available video tracks.
+@param p_mi: media player
+@return: the number of available video tracks (int)
+"""
+
+if hasattr(dll, 'libvlc_video_get_track_description'):
+ p = ctypes.CFUNCTYPE(ctypes.POINTER(TrackDescription), MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_track_description = p( ('libvlc_video_get_track_description', dll), f )
+ libvlc_video_get_track_description.__doc__ = """Get the description of available video tracks.
+@param p_mi: media player
+@return: list with description of available video tracks, or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_video_get_track'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_video_get_track = p( ('libvlc_video_get_track', dll), f )
+ libvlc_video_get_track.__doc__ = """Get current video track.
+@param p_mi: media player
+@return: the video track (int) or -1 if none
+"""
+
+if hasattr(dll, 'libvlc_video_set_track'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_video_set_track = p( ('libvlc_video_set_track', dll), f )
+ libvlc_video_set_track.__doc__ = """Set video track.
+@param p_mi: media player
+@param i_track: the track (int)
+@return: 0 on success, -1 if out of range
+"""
+
+if hasattr(dll, 'libvlc_video_take_snapshot'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.c_char_p, ctypes.c_int, ctypes.c_int)
+ f = ((1,), (1,), (1,), (1,), (1,),)
+ libvlc_video_take_snapshot = p( ('libvlc_video_take_snapshot', dll), f )
+ libvlc_video_take_snapshot.__doc__ = """Take a snapshot of the current video window.
+If i_width AND i_height is 0, original size is used.
+If i_width XOR i_height is 0, original aspect-ratio is preserved.
+@param p_mi: media player instance
+@param num: number of video output (typically 0 for the first/only one)
+@param psz_filepath: the path where to save the screenshot to
+@param i_width: the snapshot's width
+@param i_height: the snapshot's height
+@return: 0 on success, -1 if the video was not found
+"""
+
+if hasattr(dll, 'libvlc_video_set_deinterlace'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_video_set_deinterlace = p( ('libvlc_video_set_deinterlace', dll), f )
+ libvlc_video_set_deinterlace.__doc__ = """Enable or disable deinterlace filter
+@param p_mi: libvlc media player
+@param psz_mode: type of deinterlace filter, NULL to disable
+"""
+
+if hasattr(dll, 'libvlc_video_get_marquee_int'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_get_marquee_int = p( ('libvlc_video_get_marquee_int', dll), f )
+ libvlc_video_get_marquee_int.__doc__ = """Get an integer marquee option value
+@param p_mi: libvlc media player
+@param option: marq option to get See libvlc_video_marquee_int_option_t
+"""
+
+if hasattr(dll, 'libvlc_video_get_marquee_string'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_get_marquee_string = p( ('libvlc_video_get_marquee_string', dll), f )
+ libvlc_video_get_marquee_string.__doc__ = """Get a string marquee option value
+@param p_mi: libvlc media player
+@param option: marq option to get See libvlc_video_marquee_string_option_t
+"""
+
+if hasattr(dll, 'libvlc_video_set_marquee_int'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_video_set_marquee_int = p( ('libvlc_video_set_marquee_int', dll), f )
+ libvlc_video_set_marquee_int.__doc__ = """Enable, disable or set an integer marquee option
+Setting libvlc_marquee_Enable has the side effect of enabling (arg !0)
+or disabling (arg 0) the marq filter.
+@param p_mi: libvlc media player
+@param option: marq option to set See libvlc_video_marquee_int_option_t
+@param i_val: marq option value
+"""
+
+if hasattr(dll, 'libvlc_video_set_marquee_string'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_video_set_marquee_string = p( ('libvlc_video_set_marquee_string', dll), f )
+ libvlc_video_set_marquee_string.__doc__ = """Set a marquee string option
+@param p_mi: libvlc media player
+@param option: marq option to set See libvlc_video_marquee_string_option_t
+@param psz_text: marq option value
+"""
+
+if hasattr(dll, 'libvlc_video_get_logo_int'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_get_logo_int = p( ('libvlc_video_get_logo_int', dll), f )
+ libvlc_video_get_logo_int.__doc__ = """Get integer logo option.
+@param p_mi: libvlc media player instance
+@param option: logo option to get, values of libvlc_video_logo_option_t
+"""
+
+if hasattr(dll, 'libvlc_video_set_logo_int'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_video_set_logo_int = p( ('libvlc_video_set_logo_int', dll), f )
+ libvlc_video_set_logo_int.__doc__ = """Set logo option as integer. Options that take a different type value
+are ignored.
+Passing libvlc_logo_enable as option value has the side effect of
+starting (arg !0) or stopping (arg 0) the logo filter.
+@param p_mi: libvlc media player instance
+@param option: logo option to set, values of libvlc_video_logo_option_t
+@param value: logo option value
+"""
+
+if hasattr(dll, 'libvlc_video_set_logo_string'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_video_set_logo_string = p( ('libvlc_video_set_logo_string', dll), f )
+ libvlc_video_set_logo_string.__doc__ = """Set logo option as string. Options that take a different type value
+are ignored.
+@param p_mi: libvlc media player instance
+@param option: logo option to set, values of libvlc_video_logo_option_t
+@param psz_value: logo option value
+"""
+
+if hasattr(dll, 'libvlc_video_get_adjust_int'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_get_adjust_int = p( ('libvlc_video_get_adjust_int', dll), f )
+ libvlc_video_get_adjust_int.__doc__ = """Get integer adjust option.
+@version: LibVLC 1.1.1 and later.
+@param p_mi: libvlc media player instance
+@param option: adjust option to get, values of libvlc_video_adjust_option_t
+"""
+
+if hasattr(dll, 'libvlc_video_set_adjust_int'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_video_set_adjust_int = p( ('libvlc_video_set_adjust_int', dll), f )
+ libvlc_video_set_adjust_int.__doc__ = """Set adjust option as integer. Options that take a different type value
+are ignored.
+Passing libvlc_adjust_enable as option value has the side effect of
+starting (arg !0) or stopping (arg 0) the adjust filter.
+@version: LibVLC 1.1.1 and later.
+@param p_mi: libvlc media player instance
+@param option: adust option to set, values of libvlc_video_adjust_option_t
+@param value: adjust option value
+"""
+
+if hasattr(dll, 'libvlc_video_get_adjust_float'):
+ p = ctypes.CFUNCTYPE(ctypes.c_float, MediaPlayer, ctypes.c_uint)
+ f = ((1,), (1,),)
+ libvlc_video_get_adjust_float = p( ('libvlc_video_get_adjust_float', dll), f )
+ libvlc_video_get_adjust_float.__doc__ = """Get float adjust option.
+@version: LibVLC 1.1.1 and later.
+@param p_mi: libvlc media player instance
+@param option: adjust option to get, values of libvlc_video_adjust_option_t
+"""
+
+if hasattr(dll, 'libvlc_video_set_adjust_float'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_uint, ctypes.c_float)
+ f = ((1,), (1,), (1,),)
+ libvlc_video_set_adjust_float = p( ('libvlc_video_set_adjust_float', dll), f )
+ libvlc_video_set_adjust_float.__doc__ = """Set adjust option as float. Options that take a different type value
+are ignored.
+@version: LibVLC 1.1.1 and later.
+@param p_mi: libvlc media player instance
+@param option: adust option to set, values of libvlc_video_adjust_option_t
+@param value: adjust option value
+"""
+
+if hasattr(dll, 'libvlc_audio_output_list_get'):
+ p = ctypes.CFUNCTYPE(ctypes.POINTER(AudioOutput), Instance)
+ f = ((1,),)
+ libvlc_audio_output_list_get = p( ('libvlc_audio_output_list_get', dll), f )
+ libvlc_audio_output_list_get.__doc__ = """Get the list of available audio outputs
+ In case of error, NULL is returned.
+@param p_instance: libvlc instance
+@return: list of available audio outputs. It must be freed it with
+"""
+
+if hasattr(dll, 'libvlc_audio_output_list_release'):
+ p = ctypes.CFUNCTYPE(None, ctypes.POINTER(AudioOutput))
+ f = ((1,),)
+ libvlc_audio_output_list_release = p( ('libvlc_audio_output_list_release', dll), f )
+ libvlc_audio_output_list_release.__doc__ = """Free the list of available audio outputs
+@param p_list: list with audio outputs for release
+"""
+
+if hasattr(dll, 'libvlc_audio_output_set'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_audio_output_set = p( ('libvlc_audio_output_set', dll), f )
+ libvlc_audio_output_set.__doc__ = """Set the audio output.
+Change will be applied after stop and play.
+ use psz_name of See libvlc_audio_output_t
+@param p_mi: media player
+@param psz_name: name of audio output,
+@return: true if function succeded
+"""
+
+if hasattr(dll, 'libvlc_audio_output_device_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_audio_output_device_count = p( ('libvlc_audio_output_device_count', dll), f )
+ libvlc_audio_output_device_count.__doc__ = """Get count of devices for audio output, these devices are hardware oriented
+like analor or digital output of sound card
+@param p_instance: libvlc instance
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@return: number of devices
+"""
+
+if hasattr(dll, 'libvlc_audio_output_device_longname'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_audio_output_device_longname = p( ('libvlc_audio_output_device_longname', dll), f )
+ libvlc_audio_output_device_longname.__doc__ = """Get long name of device, if not available short name given
+@param p_instance: libvlc instance
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@param i_device: device index
+@return: long name of device
+"""
+
+if hasattr(dll, 'libvlc_audio_output_device_id'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_audio_output_device_id = p( ('libvlc_audio_output_device_id', dll), f )
+ libvlc_audio_output_device_id.__doc__ = """Get id name of device
+@param p_instance: libvlc instance
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@param i_device: device index
+@return: id name of device, use for setting device, need to be free after use
+"""
+
+if hasattr(dll, 'libvlc_audio_output_device_set'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_char_p, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_audio_output_device_set = p( ('libvlc_audio_output_device_set', dll), f )
+ libvlc_audio_output_device_set.__doc__ = """Set audio output device. Changes are only effective after stop and play.
+@param p_mi: media player
+@param psz_audio_output: - name of audio output, See libvlc_audio_output_t
+@param psz_device_id: device
+"""
+
+if hasattr(dll, 'libvlc_audio_output_get_device_type'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_output_get_device_type = p( ('libvlc_audio_output_get_device_type', dll), f )
+ libvlc_audio_output_get_device_type.__doc__ = """Get current audio device type. Device type describes something like
+character of output sound - stereo sound, 2.1, 5.1 etc
+@param p_mi: media player
+@return: the audio devices type See libvlc_audio_output_device_types_t
+"""
+
+if hasattr(dll, 'libvlc_audio_output_set_device_type'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_audio_output_set_device_type = p( ('libvlc_audio_output_set_device_type', dll), f )
+ libvlc_audio_output_set_device_type.__doc__ = """Set current audio device type.
+@param p_mi: vlc instance
+@param device_type: the audio device type,
+"""
+
+if hasattr(dll, 'libvlc_audio_toggle_mute'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_toggle_mute = p( ('libvlc_audio_toggle_mute', dll), f )
+ libvlc_audio_toggle_mute.__doc__ = """Toggle mute status.
+@param p_mi: media player
+"""
+
+if hasattr(dll, 'libvlc_audio_get_mute'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_get_mute = p( ('libvlc_audio_get_mute', dll), f )
+ libvlc_audio_get_mute.__doc__ = """Get current mute status.
+@param p_mi: media player
+@return: the mute status (boolean)
+"""
+
+if hasattr(dll, 'libvlc_audio_set_mute'):
+ p = ctypes.CFUNCTYPE(None, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_audio_set_mute = p( ('libvlc_audio_set_mute', dll), f )
+ libvlc_audio_set_mute.__doc__ = """Set mute status.
+@param p_mi: media player
+@param status: If status is true then mute, otherwise unmute
+"""
+
+if hasattr(dll, 'libvlc_audio_get_volume'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_get_volume = p( ('libvlc_audio_get_volume', dll), f )
+ libvlc_audio_get_volume.__doc__ = """Get current audio level.
+@param p_mi: media player
+@return: the audio level (int)
+"""
+
+if hasattr(dll, 'libvlc_audio_set_volume'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_audio_set_volume = p( ('libvlc_audio_set_volume', dll), f )
+ libvlc_audio_set_volume.__doc__ = """Set current audio level.
+@param p_mi: media player
+@param i_volume: the volume (int)
+@return: 0 if the volume was set, -1 if it was out of range
+"""
+
+if hasattr(dll, 'libvlc_audio_get_track_count'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_get_track_count = p( ('libvlc_audio_get_track_count', dll), f )
+ libvlc_audio_get_track_count.__doc__ = """Get number of available audio tracks.
+@param p_mi: media player
+@return: the number of available audio tracks (int), or -1 if unavailable
+"""
+
+if hasattr(dll, 'libvlc_audio_get_track_description'):
+ p = ctypes.CFUNCTYPE(ctypes.POINTER(TrackDescription), MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_get_track_description = p( ('libvlc_audio_get_track_description', dll), f )
+ libvlc_audio_get_track_description.__doc__ = """Get the description of available audio tracks.
+@param p_mi: media player
+@return: list with description of available audio tracks, or NULL
+"""
+
+if hasattr(dll, 'libvlc_audio_get_track'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_get_track = p( ('libvlc_audio_get_track', dll), f )
+ libvlc_audio_get_track.__doc__ = """Get current audio track.
+@param p_mi: media player
+@return: the audio track (int), or -1 if none.
+"""
+
+if hasattr(dll, 'libvlc_audio_set_track'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_audio_set_track = p( ('libvlc_audio_set_track', dll), f )
+ libvlc_audio_set_track.__doc__ = """Set current audio track.
+@param p_mi: media player
+@param i_track: the track (int)
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_audio_get_channel'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_get_channel = p( ('libvlc_audio_get_channel', dll), f )
+ libvlc_audio_get_channel.__doc__ = """Get current audio channel.
+@param p_mi: media player
+@return: the audio channel See libvlc_audio_output_channel_t
+"""
+
+if hasattr(dll, 'libvlc_audio_set_channel'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_int)
+ f = ((1,), (1,),)
+ libvlc_audio_set_channel = p( ('libvlc_audio_set_channel', dll), f )
+ libvlc_audio_set_channel.__doc__ = """Set current audio channel.
+@param p_mi: media player
+@param channel: the audio channel, See libvlc_audio_output_channel_t
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_audio_get_delay'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int64, MediaPlayer)
+ f = ((1,),)
+ libvlc_audio_get_delay = p( ('libvlc_audio_get_delay', dll), f )
+ libvlc_audio_get_delay.__doc__ = """Get current audio delay.
+@version: LibVLC 1.1.1 or later
+@param p_mi: media player
+@return: the audio delay (microseconds)
+"""
+
+if hasattr(dll, 'libvlc_audio_set_delay'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, MediaPlayer, ctypes.c_int64)
+ f = ((1,), (1,),)
+ libvlc_audio_set_delay = p( ('libvlc_audio_set_delay', dll), f )
+ libvlc_audio_set_delay.__doc__ = """Set current audio delay. The audio delay will be reset to zero each time the media changes.
+@version: LibVLC 1.1.1 or later
+@param p_mi: media player
+@param i_delay: the audio delay (microseconds)
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_release'):
+ p = ctypes.CFUNCTYPE(None, Instance)
+ f = ((1,),)
+ libvlc_vlm_release = p( ('libvlc_vlm_release', dll), f )
+ libvlc_vlm_release.__doc__ = """Release the vlm instance related to the given libvlc_instance_t
+@param p_instance: the instance
+"""
+
+if hasattr(dll, 'libvlc_vlm_add_broadcast'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_int)
+ f = ((1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,),)
+ libvlc_vlm_add_broadcast = p( ('libvlc_vlm_add_broadcast', dll), f )
+ libvlc_vlm_add_broadcast.__doc__ = """Add a broadcast, with one input.
+@param p_instance: the instance
+@param psz_name: the name of the new broadcast
+@param psz_input: the input MRL
+@param psz_output: the output MRL (the parameter to the "sout" variable)
+@param i_options: number of additional options
+@param ppsz_options: additional options
+@param b_enabled: boolean for enabling the new broadcast
+@param b_loop: Should this broadcast be played in loop ?
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_add_vod'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_char_p)
+ f = ((1,), (1,), (1,), (1,), (1,), (1,), (1,),)
+ libvlc_vlm_add_vod = p( ('libvlc_vlm_add_vod', dll), f )
+ libvlc_vlm_add_vod.__doc__ = """Add a vod, with one input.
+@param p_instance: the instance
+@param psz_name: the name of the new vod media
+@param psz_input: the input MRL
+@param i_options: number of additional options
+@param ppsz_options: additional options
+@param b_enabled: boolean for enabling the new vod
+@param psz_mux: the muxer of the vod media
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_del_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_vlm_del_media = p( ('libvlc_vlm_del_media', dll), f )
+ libvlc_vlm_del_media.__doc__ = """Delete a media (VOD or broadcast).
+@param p_instance: the instance
+@param psz_name: the media to delete
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_set_enabled'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_set_enabled = p( ('libvlc_vlm_set_enabled', dll), f )
+ libvlc_vlm_set_enabled.__doc__ = """Enable or disable a media (VOD or broadcast).
+@param p_instance: the instance
+@param psz_name: the media to work on
+@param b_enabled: the new status
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_set_output'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_set_output = p( ('libvlc_vlm_set_output', dll), f )
+ libvlc_vlm_set_output.__doc__ = """Set the output for a media.
+@param p_instance: the instance
+@param psz_name: the media to work on
+@param psz_output: the output MRL (the parameter to the "sout" variable)
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_set_input'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_set_input = p( ('libvlc_vlm_set_input', dll), f )
+ libvlc_vlm_set_input.__doc__ = """Set a media's input MRL. This will delete all existing inputs and
+add the specified one.
+@param p_instance: the instance
+@param psz_name: the media to work on
+@param psz_input: the input MRL
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_add_input'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_add_input = p( ('libvlc_vlm_add_input', dll), f )
+ libvlc_vlm_add_input.__doc__ = """Add a media's input MRL. This will add the specified one.
+@param p_instance: the instance
+@param psz_name: the media to work on
+@param psz_input: the input MRL
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_set_loop'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_set_loop = p( ('libvlc_vlm_set_loop', dll), f )
+ libvlc_vlm_set_loop.__doc__ = """Set a media's loop status.
+@param p_instance: the instance
+@param psz_name: the media to work on
+@param b_loop: the new status
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_set_mux'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_set_mux = p( ('libvlc_vlm_set_mux', dll), f )
+ libvlc_vlm_set_mux.__doc__ = """Set a media's vod muxer.
+@param p_instance: the instance
+@param psz_name: the media to work on
+@param psz_mux: the new muxer
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_change_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_int)
+ f = ((1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,),)
+ libvlc_vlm_change_media = p( ('libvlc_vlm_change_media', dll), f )
+ libvlc_vlm_change_media.__doc__ = """Edit the parameters of a media. This will delete all existing inputs and
+add the specified one.
+@param p_instance: the instance
+@param psz_name: the name of the new broadcast
+@param psz_input: the input MRL
+@param psz_output: the output MRL (the parameter to the "sout" variable)
+@param i_options: number of additional options
+@param ppsz_options: additional options
+@param b_enabled: boolean for enabling the new broadcast
+@param b_loop: Should this broadcast be played in loop ?
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_play_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_vlm_play_media = p( ('libvlc_vlm_play_media', dll), f )
+ libvlc_vlm_play_media.__doc__ = """Play the named broadcast.
+@param p_instance: the instance
+@param psz_name: the name of the broadcast
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_stop_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_vlm_stop_media = p( ('libvlc_vlm_stop_media', dll), f )
+ libvlc_vlm_stop_media.__doc__ = """Stop the named broadcast.
+@param p_instance: the instance
+@param psz_name: the name of the broadcast
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_pause_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_vlm_pause_media = p( ('libvlc_vlm_pause_media', dll), f )
+ libvlc_vlm_pause_media.__doc__ = """Pause the named broadcast.
+@param p_instance: the instance
+@param psz_name: the name of the broadcast
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_seek_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_float)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_seek_media = p( ('libvlc_vlm_seek_media', dll), f )
+ libvlc_vlm_seek_media.__doc__ = """Seek in the named broadcast.
+@param p_instance: the instance
+@param psz_name: the name of the broadcast
+@param f_percentage: the percentage to seek to
+@return: 0 on success, -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_show_media'):
+ p = ctypes.CFUNCTYPE(ctypes.c_char_p, Instance, ctypes.c_char_p)
+ f = ((1,), (1,),)
+ libvlc_vlm_show_media = p( ('libvlc_vlm_show_media', dll), f )
+ libvlc_vlm_show_media.__doc__ = """Return information about the named media as a JSON
+string representation.
+This function is mainly intended for debugging use,
+if you want programmatic access to the state of
+a vlm_media_instance_t, please use the corresponding
+libvlc_vlm_get_media_instance_xxx -functions.
+Currently there are no such functions available for
+vlm_media_t though.
+ if the name is an empty string, all media is described
+@param p_instance: the instance
+@param psz_name: the name of the media,
+@return: string with information about named media, or NULL on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_media_instance_position'):
+ p = ctypes.CFUNCTYPE(ctypes.c_float, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_get_media_instance_position = p( ('libvlc_vlm_get_media_instance_position', dll), f )
+ libvlc_vlm_get_media_instance_position.__doc__ = """Get vlm_media instance position by name or instance id
+@param p_instance: a libvlc instance
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: position as float or -1. on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_media_instance_time'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_get_media_instance_time = p( ('libvlc_vlm_get_media_instance_time', dll), f )
+ libvlc_vlm_get_media_instance_time.__doc__ = """Get vlm_media instance time by name or instance id
+@param p_instance: a libvlc instance
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: time as integer or -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_media_instance_length'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_get_media_instance_length = p( ('libvlc_vlm_get_media_instance_length', dll), f )
+ libvlc_vlm_get_media_instance_length.__doc__ = """Get vlm_media instance length by name or instance id
+@param p_instance: a libvlc instance
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: length of media item or -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_media_instance_rate'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_get_media_instance_rate = p( ('libvlc_vlm_get_media_instance_rate', dll), f )
+ libvlc_vlm_get_media_instance_rate.__doc__ = """Get vlm_media instance playback rate by name or instance id
+@param p_instance: a libvlc instance
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: playback rate or -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_media_instance_title'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_get_media_instance_title = p( ('libvlc_vlm_get_media_instance_title', dll), f )
+ libvlc_vlm_get_media_instance_title.__doc__ = """Get vlm_media instance title number by name or instance id
+@bug: will always return 0
+@param p_instance: a libvlc instance
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: title as number or -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_media_instance_chapter'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_get_media_instance_chapter = p( ('libvlc_vlm_get_media_instance_chapter', dll), f )
+ libvlc_vlm_get_media_instance_chapter.__doc__ = """Get vlm_media instance chapter number by name or instance id
+@bug: will always return 0
+@param p_instance: a libvlc instance
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: chapter as number or -1 on error
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_media_instance_seekable'):
+ p = ctypes.CFUNCTYPE(ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
+ f = ((1,), (1,), (1,),)
+ libvlc_vlm_get_media_instance_seekable = p( ('libvlc_vlm_get_media_instance_seekable', dll), f )
+ libvlc_vlm_get_media_instance_seekable.__doc__ = """Is libvlc instance seekable ?
+@bug: will always return 0
+@param p_instance: a libvlc instance
+@param psz_name: name of vlm media instance
+@param i_instance: instance id
+@return: 1 if seekable, 0 if not, -1 if media does not exist
+"""
+
+if hasattr(dll, 'libvlc_vlm_get_event_manager'):
+ p = ctypes.CFUNCTYPE(EventManager, Instance)
+ f = ((1,),)
+ libvlc_vlm_get_event_manager = p( ('libvlc_vlm_get_event_manager', dll), f )
+ libvlc_vlm_get_event_manager.__doc__ = """Get libvlc_event_manager from a vlm media.
+The p_event_manager is immutable, so you don't have to hold the lock
+@param p_instance: a libvlc instance
+@return: libvlc_event_manager
+"""
+
+### Start of footer.py ###
+
+def callbackmethod(f):
+ """Backward compatibility with the now useless @callbackmethod decorator.
+
+ This method will be removed after a transition period.
+ """
+ return f
+
+# Example callback, useful for debugging
+def debug_callback(event, *args, **kwds):
+ l = ["event %s" % (event.type,)]
+ if args:
+ l.extend(map(str, args))
+ if kwds:
+ l.extend(sorted( "%s=%s" % t for t in kwds.iteritems() ))
+ print "Debug callback (%s)" % ", ".join(l)
+
+if __name__ == '__main__':
+ try:
+ from msvcrt import getch
+ except ImportError:
+ def getch():
+ import tty
+ import termios
+ fd=sys.stdin.fileno()
+ old_settings=termios.tcgetattr(fd)
+ try:
+ tty.setraw(fd)
+ ch=sys.stdin.read(1)
+ finally:
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
+ return ch
+
+ def end_callback(event):
+ print "End of media stream (event %s)" % event.type
+ sys.exit(0)
+
+ echo_position = False
+ def pos_callback(event, player):
+ if echo_position:
+ print "%s to %.2f%% (%.2f%%)\r" % (event.type,
+ event.u.new_position * 100,
+ player.get_position() * 100)
+
+ def print_version():
+ """Print libvlc version.
+ """
+ try:
+ print "LibVLC version", libvlc_get_version()
+ except:
+ print "Error:", sys.exc_info()[1]
+
+ if sys.argv[1:]:
+ instance = Instance()
+ try:
+ # load marq option
+ media = instance.media_new(sys.argv[1], "sub-filter=marq")
+ except NameError:
+ print "NameError:", sys.exc_info()[1], "(VLC release too old?)"
+ sys.exit(1)
+ player = instance.media_player_new()
+ player.set_media(media)
+ player.play()
+
+ # Some marquee examples. Marquee requires 'sub-filter=marq' in the
+ # media_new() call above. See also the Media.add_options method.
+ # <http://www.videolan.org/doc/play-howto/en/ch04.html>
+ player.video_set_marquee_int(VideoMarqueeOption.Enable, 1)
+ player.video_set_marquee_int(VideoMarqueeOption.Size, 24) # pixels
+ player.video_set_marquee_int(VideoMarqueeOption.Position, Position.Bottom)
+ if False: # only one marquee can be specified
+ player.video_set_marquee_int(VideoMarqueeOption.Timeout, 5000) # millisec, 0=forever
+ t = media.get_mrl() # movie
+ else: # update marquee text periodically
+ player.video_set_marquee_int(VideoMarqueeOption.Timeout, 0) # millisec, 0=forever
+ player.video_set_marquee_int(VideoMarqueeOption.Refresh, 1000) # millisec (or sec?)
+ t = '%Y-%m-%d %H:%M:%S'
+ player.video_set_marquee_string(VideoMarqueeOption.Text, t)
+
+ # Some event manager examples. Note, the callback can be any Python
+ # callable and does not need to be decorated. Optionally, specify
+ # any number of positional and/or keyword arguments to be passed
+ # to the callback (in addition to the first one, an Event instance).
+ event_manager = player.event_manager()
+ event_manager.event_attach(EventType.MediaPlayerEndReached, end_callback)
+ event_manager.event_attach(EventType.MediaPlayerPositionChanged, pos_callback, player)
+
+ def print_info():
+ """Print information about the media."""
+ try:
+ print_version()
+ media = player.get_media()
+ print "State:", player.get_state()
+ print "Media:", media.get_mrl()
+ print "Track:", player.video_get_track(), "/", player.video_get_track_count()
+ print "Current time:", player.get_time(), "/", media.get_duration()
+ print "Position:", player.get_position()
+ print "FPS:", player.get_fps()
+ print "Rate:", player.get_rate()
+ print "Video size: (%d, %d)" % player.video_get_size(0)
+ print "Scale:", player.video_get_scale()
+ print "Aspect ratio:", player.video_get_aspect_ratio()
+ except Exception:
+ print "Error:", sys.exc_info()[1]
+
+ def forward():
+ """Go forward 1s"""
+ player.set_time(player.get_time() + 1000)
+
+ def backward():
+ """Go backward 1s"""
+ player.set_time(player.get_time() - 1000)
+
+ def one_frame_forward():
+ """Go forward one frame"""
+ player.set_time(player.get_time() + long(1000 / (player.get_fps() or 25)))
+
+ def one_frame_backward():
+ """Go backward one frame"""
+ player.set_time(player.get_time() - long(1000 / (player.get_fps() or 25)))
+
+ def print_help():
+ """Print help
+ """
+ print "Single-character commands:"
+ for k, m in keybindings.iteritems():
+ print " %s: %s" % (k, (m.__doc__ or m.__name__).splitlines()[0].rstrip("."))
+ print " 1-9: go to the given fraction of the movie"
+
+ def quit_app():
+ """Exit."""
+ sys.exit(0)
+
+ def toggle_echo_position():
+ """Toggle echoing of media position"""
+ global echo_position
+ echo_position = not echo_position
+
+ keybindings={
+ ' ': player.pause,
+ '+': forward,
+ '-': backward,
+ '.': one_frame_forward,
+ ',': one_frame_backward,
+ '?': print_help,
+ 'f': player.toggle_fullscreen,
+ 'i': print_info,
+ 'p': toggle_echo_position,
+ 'q': quit_app,
+ }
+
+ print "Press q to quit, ? to get help."
+ print
+ while True:
+ k = getch()
+ print ">", k
+ if k in keybindings:
+ keybindings[k]()
+ elif k.isdigit():
+ # Numeric value. Jump to a fraction of the movie.
+ player.set_position(float('0.'+k))
+ else:
+ print "Syntax: %s <movie_filename>" % sys.argv[0]
+ print "Once launched, type ? to get help."
+ print_version()
+
+
+
+
+# 12 methods not wrapped :
+# libvlc_audio_output_list_release
+# libvlc_clearerr
+# libvlc_errmsg
+# libvlc_event_type_name
+# libvlc_free
+# libvlc_get_changeset
+# libvlc_get_compiler
+# libvlc_get_version
+# libvlc_new
+# libvlc_set_exit_handler
+# libvlc_track_description_release
+# libvlc_video_set_callbacks
\ No newline at end of file
diff --git a/vlcwidget.py b/vlcwidget.py
new file mode 100644
index 0000000..56ff6dd
--- /dev/null
+++ b/vlcwidget.py
@@ -0,0 +1,114 @@
+#! /usr/bin/python
+
+"""VLC Widget classes.
+
+This module provides two helper classes, to ease the embedding of a
+VLC component inside a pygtk application.
+
+VLCWidget is a simple VLC widget.
+
+DecoratedVLCWidget provides simple player controls.
+
+$Id$
+"""
+
+import gtk
+import sys
+import vlc
+
+from gettext import gettext as _
+
+class VLCWidget(gtk.DrawingArea):
+ """Simple VLC widget.
+
+ Its player can be controlled through the 'player' attribute, which
+ is a MediaControl instance.
+ """
+ def __init__(self, *p):
+ gtk.DrawingArea.__init__(self)
+ self.player=vlc.MediaControl(*p)
+ def handle_embed(*p):
+ if sys.platform == 'win32':
+ xidattr='handle'
+ else:
+ xidattr='xid'
+ self.player.set_visual(getattr(self.window, xidattr))
+ return True
+ self.connect("map-event", handle_embed)
+ self.set_size_request(320, 200)
+
+
+class DecoratedVLCWidget(gtk.VBox):
+ """Decorated VLC widget.
+
+ VLC widget decorated with a player control toolbar.
+
+ Its player can be controlled through the 'player' attribute, which
+ is a MediaControl instance.
+ """
+ def __init__(self, *p):
+ gtk.VBox.__init__(self)
+ self._vlc_widget=VLCWidget(*p)
+ self.player=self._vlc_widget.player
+ self.pack_start(self._vlc_widget, expand=True)
+ self._toolbar = self.get_player_control_toolbar()
+ self.pack_start(self._toolbar, expand=False)
+
+ def get_player_control_toolbar(self):
+ """Return a player control toolbar
+ """
+ tb=gtk.Toolbar()
+ tb.set_style(gtk.TOOLBAR_ICONS)
+
+ def on_play(b):
+ self.player.start(0)
+ return True
+
+ def on_stop(b):
+ self.player.stop(0)
+ return True
+
+ def on_pause(b):
+ self.player.pause(0)
+ return True
+
+ tb_list = (
+ (_("Play"), _("Play"), gtk.STOCK_MEDIA_PLAY,
+ on_play),
+ (_("Pause"), _("Pause"), gtk.STOCK_MEDIA_PAUSE,
+ on_pause),
+ (_("Stop"), _("Stop"), gtk.STOCK_MEDIA_STOP,
+ on_stop),
+ )
+
+ for text, tooltip, stock, callback in tb_list:
+ b=gtk.ToolButton(stock)
+ b.connect("clicked", callback)
+ tb.insert(b, -1)
+ tb.show_all()
+ return tb
+
+class VideoPlayer:
+ """Example video player.
+ """
+ def __init__(self):
+ self.vlc = DecoratedVLCWidget()
+
+ def main(self, fname):
+ self.vlc.player.set_mrl(fname)
+ self.popup()
+ gtk.main()
+
+ def popup(self):
+ w=gtk.Window()
+ w.add(self.vlc)
+ w.show_all()
+ w.connect("destroy", gtk.main_quit)
+ return w
+
+if __name__ == '__main__':
+ if not sys.argv[1:]:
+ print "You must provide a movie filename"
+ sys.exit(1)
+ p=VideoPlayer()
+ p.main(sys.argv[1])
\ No newline at end of file
|
hadley/toc-vis
|
a25304d5b810126a1e0b0763269c4b7ceee550fd
|
A few more tweaks
|
diff --git a/3-download-pages.r b/3-download-pages.r
index bd35193..3393c89 100644
--- a/3-download-pages.r
+++ b/3-download-pages.r
@@ -1,30 +1,31 @@
library(plyr)
isbn <- scan("isbns.txt", "")
url <- paste("http://search.barnesandnoble.com///e/", isbn, sep = "")
-# Download html file
+# Download html file from B&N
for(i in seq_along(isbn)) {
path <- paste("books/", isbn[i], ".html", sep = "")
if (file.exists(path)) {
cat(".")
next
}
download.file(url[i], path, quiet = T)
# Avoids B&N throttling
Sys.sleep(5)
cat(".")
}
cat("\n")
# grep -c "name=\"TOC\"" *.html | cut -d: -f2 | sort | uniq -c
-
# Convert html to json
input <- paste("books/", isbn, ".html", sep = "")
output <- paste("json/", isbn, ".json", sep = "")
cmd <- paste("parsley extract-toc.json", input, "-o", output)
-l_ply(cmd, system)
\ No newline at end of file
+l_ply(cmd, system)
+
+# grep -c "toc-table" *.html | cut -d: -f2 | sort | uniq -c
diff --git a/extract-toc.json b/extract-toc.json
index 7f657d0..9f0f17c 100644
--- a/extract-toc.json
+++ b/extract-toc.json
@@ -1,22 +1,23 @@
{
"title?": "replace(h1, ' by.*', '', '')",
"authors?": [".nl a"],
"published?": "replace(#product-info .pubDate, 'Pub. Date: ', '', '')",
"pages?": "replace(.product-list-info li:nth-child(2), '[^.0-9]', 'g', '')",
"isbn?": ".isbn .isbn-a",
"format?": "normalize-space(.format)",
"price?": "replace(.list-price, '[^.0-9]', 'g', '')",
"subject?": "#header-breadcrumbs :nth-child(3)",
"series?": ".series a",
"toc-table(#toc tr)?": [{
"section": "td:nth-child(1)",
"title": "td:nth-child(2)",
"page": "td:nth-child(3)"
}],
"toc-paragraph?": ["#toc p"],
+ "toc-raw?": "#toc",
"description?": [".wrap6r p"],
}
\ No newline at end of file
|
hadley/toc-vis
|
8488a4df63a9aaf6907c02de1ddd116de7176fb6
|
Refine extractor parselet
|
diff --git a/extract-toc.json b/extract-toc.json
index 6132bad..7f657d0 100644
--- a/extract-toc.json
+++ b/extract-toc.json
@@ -1,16 +1,22 @@
{
- "title": "h1",
- "published?": "#product-info .pubDate",
- "series?": ".series a",
+ "title?": "replace(h1, ' by.*', '', '')",
"authors?": [".nl a"],
+
+ "published?": "replace(#product-info .pubDate, 'Pub. Date: ', '', '')",
+ "pages?": "replace(.product-list-info li:nth-child(2), '[^.0-9]', 'g', '')",
+ "isbn?": ".isbn .isbn-a",
+ "format?": "normalize-space(.format)",
+ "price?": "replace(.list-price, '[^.0-9]', 'g', '')",
+
"subject?": "#header-breadcrumbs :nth-child(3)",
- "format?": ".format",
- "price?": ".list-price",
+ "series?": ".series a",
+
"toc-table(#toc tr)?": [{
"section": "td:nth-child(1)",
"title": "td:nth-child(2)",
"page": "td:nth-child(3)"
}],
"toc-paragraph?": ["#toc p"],
+ "description?": [".wrap6r p"],
}
\ No newline at end of file
|
hadley/toc-vis
|
d2494cdfc7de274d9452715caeff136bf7accc80
|
Parse json files
|
diff --git a/.gitignore b/.gitignore
index 447c403..0b64a7c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
-books
\ No newline at end of file
+books
+json
\ No newline at end of file
diff --git a/3-download-pages.r b/3-download-pages.r
index 5561799..bd35193 100644
--- a/3-download-pages.r
+++ b/3-download-pages.r
@@ -1,16 +1,30 @@
+library(plyr)
+
isbn <- scan("isbns.txt", "")
url <- paste("http://search.barnesandnoble.com///e/", isbn, sep = "")
+# Download html file
for(i in seq_along(isbn)) {
path <- paste("books/", isbn[i], ".html", sep = "")
if (file.exists(path)) {
cat(".")
next
}
download.file(url[i], path, quiet = T)
# Avoids B&N throttling
Sys.sleep(5)
cat(".")
}
-cat("\n")
\ No newline at end of file
+cat("\n")
+
+# grep -c "name=\"TOC\"" *.html | cut -d: -f2 | sort | uniq -c
+
+
+# Convert html to json
+
+input <- paste("books/", isbn, ".html", sep = "")
+output <- paste("json/", isbn, ".json", sep = "")
+cmd <- paste("parsley extract-toc.json", input, "-o", output)
+
+l_ply(cmd, system)
\ No newline at end of file
diff --git a/extract-toc.json b/extract-toc.json
index c141951..6132bad 100644
--- a/extract-toc.json
+++ b/extract-toc.json
@@ -1,3 +1,16 @@
{
- "toc": "#toc"
+ "title": "h1",
+ "published?": "#product-info .pubDate",
+ "series?": ".series a",
+ "authors?": [".nl a"],
+ "subject?": "#header-breadcrumbs :nth-child(3)",
+ "format?": ".format",
+ "price?": ".list-price",
+ "toc-table(#toc tr)?": [{
+ "section": "td:nth-child(1)",
+ "title": "td:nth-child(2)",
+ "page": "td:nth-child(3)"
+ }],
+ "toc-paragraph?": ["#toc p"],
+
}
\ No newline at end of file
|
niner/CiderCMS
|
1d794aff95807836eed0f072dbc05ed79d5db71e
|
Add missing templates needed for tests
|
diff --git a/t/test.example/templates/types/site.zpt b/t/test.example/templates/types/site.zpt
new file mode 100644
index 0000000..5af9ce2
--- /dev/null
+++ b/t/test.example/templates/types/site.zpt
@@ -0,0 +1,6 @@
+<div xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS" tal:omit-tag="">
+ <div tal:condition="true: management" class="folder"><a tal:attributes="href self/uri_management" tal:content="self/property --title"/></div>
+ <div tal:condition="false: management" tal:repeat="child self/children" tal:omit-tag="">
+ <div tal:condition="true: child/type/page_element" tal:replace="structure child/render"/>
+ </div>
+</div>
diff --git a/t/test.example/templates/types/textfield.zpt b/t/test.example/templates/types/textfield.zpt
new file mode 100644
index 0000000..889bc87
--- /dev/null
+++ b/t/test.example/templates/types/textfield.zpt
@@ -0,0 +1 @@
+<div xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS" tal:attributes="id string:object_${self/id}" tal:content="structure self/property --text"/>
|
niner/CiderCMS
|
350359218f227332ffc8c1c7b2e7dd34b77059fd
|
Make authentication a little more flexible
|
diff --git a/lib/CiderCMS/User.pm b/lib/CiderCMS/User.pm
index 2aca511..89086ba 100644
--- a/lib/CiderCMS/User.pm
+++ b/lib/CiderCMS/User.pm
@@ -1,231 +1,232 @@
package CiderCMS::User;
use Moose;
use namespace::autoclean;
extends 'Catalyst::Authentication::User';
use List::MoreUtils 'all';
use Try::Tiny;
use Scalar::Util qw(blessed);
has 'config' => (is => 'rw');
has '_user' => (is => 'rw');
has '_roles' => (is => 'rw');
sub new {
my ( $class, $config, $c) = @_;
my $self = {
config => $config,
_roles => undef,
_user => undef
};
bless $self, $class;
return $self;
}
sub load {
my ($self, $authinfo, $c) = @_;
Catalyst::Exception->throw(
"parent field not present in authentication data. Missing in your login form?"
) unless $authinfo->{parent};
Catalyst::Exception->throw(
"parent_attr field not present in authentication data. Missing in your login form?"
) unless $authinfo->{parent_attr};
my $parent = $c->model('DB')->get_object($c, delete $authinfo->{parent});
Catalyst::Exception->throw(
"Object $authinfo->{parent} not found. Check the parent field in your login form."
) unless $parent;
my $attribute = $parent->attribute(delete $authinfo->{parent_attr});
Catalyst::Exception->throw(
"Object $authinfo->{parent} has no attribute $authinfo->{parent_attr}"
) unless $attribute;
Catalyst::Exception->throw("Attribute $attribute cannot contain user objects")
unless $attribute->can('filtered');
+ $authinfo->{$_} or delete $authinfo->{$_} foreach keys %$authinfo;
my @users = $attribute->filtered(%$authinfo);
return undef unless @users == 1;
my $user = $users[0];
Catalyst::Exception->throw("User has no password attribute")
unless $user->attribute('password');
$self->_user($user);
return $self->get_object ? $self : undef;
}
sub supported_features {
my $self = shift;
return {
session => 1,
};
}
sub roles {
my ( $self ) = shift;
Catalyst::Exception->throw("user->roles accessed, but roles not supported yet");
}
sub for_session {
my $self = shift;
return $self->_user->{id};
}
sub from_session {
my ($self, $frozenuser, $c) = @_;
$self->_user($c->model('DB')->get_object($c, $frozenuser));
return $self->_user ? $self : undef;
}
sub get {
my ($self, $field) = @_;
return $self->_user->property($field);
}
sub get_object {
my ($self, $force) = @_;
return $self->_user;
}
sub obj {
my ($self, $force) = @_;
return $self->get_object($force);
}
sub can {
my $self = shift;
return $self->SUPER::can(@_) || do {
my ($method) = @_;
if (my $code = $self->_user->can($method)) {
sub { shift->_user->$code(@_) }
}
else {
undef;
}
};
}
sub AUTOLOAD {
my $self = shift;
(my $method) = (our $AUTOLOAD =~ /([^:]+)$/);
return if $method eq "DESTROY";
if (my $code = $self->_user->can($method)) {
return $self->_user->$code(@_);
}
else {
# XXX this should also throw
return undef;
}
}
__PACKAGE__->meta->make_immutable(inline_constructor => 0);
1;
__END__
=head1 NAME
CiderCMS::User - The backing user
class for the Catalyst::Authentication::Store::CiderCMS storage
module.
=head1 SYNOPSIS
Internal - not used directly, please see
L<Catalyst::Authentication::Store::CiderCMS> for details on how to
use this module. If you need more information than is present there, read the
source.
=head1 DESCRIPTION
The CiderCMS::User class implements user storage
connected to an underlying CiderCMS instance.
=head1 SUBROUTINES / METHODS
=head2 new
Constructor.
=head2 load ( $authinfo, $c )
Retrieves a user from storage using the information provided in $authinfo.
=head2 supported_features
Indicates the features supported by this class. This is currently just Session.
=head2 roles
Not yet supported.
=head2 for_session
Returns a serialized user for storage in the session.
=head2 from_session
Revives a serialized user from storage in the session.
=head2 get ( $fieldname )
Returns the value of $fieldname for the user in question.
=head2 get_object
Retrieves the CiderCMS::Object that corresponds to this user
=head2 obj (method)
Synonym for get_object
=head2 AUTOLOAD
Delegates method calls to the underlieing user object.
=head2 can
Delegates handling of the C<< can >> method to the underlieing user object.
=head1 BUGS AND LIMITATIONS
None known currently, please email the author if you find any.
=head1 AUTHOR
Jason Kuri ([email protected])
Stefan Seifert ([email protected])
=head1 CONTRIBUTORS
Matt S Trout (mst) <[email protected]>
(fixes wrt can/AUTOLOAD sponsored by L<http://reask.com/>)
=head1 LICENSE
Copyright (c) 2007-2010 the aforementioned authors. All rights
reserved. This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.
=cut
|
niner/CiderCMS
|
ec90617da68bdea03306fcf28d1305b8135040b8
|
Fix pasting a single element
|
diff --git a/root/static/js/scripts.js b/root/static/js/scripts.js
index 1f0138c..3b39ef9 100644
--- a/root/static/js/scripts.js
+++ b/root/static/js/scripts.js
@@ -1,54 +1,54 @@
'use strict;'
function find_selected_ids() {
var checkboxes = document.querySelectorAll('input.cidercms_multi_selector');
var ids = [];
[].forEach.call(checkboxes, function (checkbox) {
if (checkbox.checked)
ids.push(checkbox.getAttribute('data-id'));
});
return ids;
}
function cut(id) {
var selected = find_selected_ids();
if (selected.length)
id = selected.join(',')
document.cookie = 'id=' + id + '; path=/'
return;
}
function paste(link, after) {
- var ids = document.cookie.match(/\bid=(\d+(,\d+)+)/)[1].split(',');
+ var ids = document.cookie.match(/\bid=(\d+(,\d+)*)/)[1].split(',');
var href = link.href;
ids.forEach(function(id) {
href += ';id=' + id;
});
if (after)
href += ';after=' + after;
location.href = href;
return false;
}
document.addEventListener("DOMContentLoaded", function() {
var edit_object_form = document.getElementById('edit_object_form');
if (edit_object_form) {
edit_object_form.onsubmit = function() {
var password = edit_object_form.querySelector('label.password input');
var repeat = edit_object_form.querySelector('label.password_repeat input');
if (password && repeat) {
var repeat_error = repeat.parentNode.querySelector('.repeat_error');
if (password.value == repeat.value) {
repeat_error.style.display = '';
return true;
}
else {
repeat_error.style.display = 'block';
alert(false);
return false;
}
}
}
}
}, false);
|
niner/CiderCMS
|
54b4ee182ca0b2a40da18d963e77b0ae2017a8d3
|
Make reservation limits available to JS
|
diff --git a/root/templates/custom/reservation/reservations.zpt b/root/templates/custom/reservation/reservations.zpt
index fd6e523..09bd297 100644
--- a/root/templates/custom/reservation/reservations.zpt
+++ b/root/templates/custom/reservation/reservations.zpt
@@ -1,48 +1,50 @@
<div
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
metal:define-macro="list"
tal:define="
reservations_attr context/attribute --reservations;
reservations_search reservations_attr/search --cancelled_by undef --start 'future';
reservations_sorted reservations_search/sort --start --end;
reservations reservations_sorted/list;
active_reservation_search reservations_attr/search --cancelled_by undef --start 'past' --start 'today' --end 'future';
active_reservation active_reservation_search/list
- ">
+ "
+ tal:attributes="data-end-limit context/property --reservation_end_limit undef; data-weekdays-limit context/property --reservation_weekdays_limit undef"
+ >
<p tal:condition="false: active_reservation" class="no_active_reservation">Frei</p>
<p tal:condition="false: reservations" class="no_reservations" id="reservations">
Keine Reservierungen eingetragen.
</p>
<table tal:condition="true: reservations" class="reservations" id="reservations">
<thead>
<tr>
<th>Datum</th>
<th>Von</th>
<th>Bis</th>
<th>Pilot</th>
</tr>
</thead>
<tbody tal:repeat="reservation reservations">
<tr tal:define="start reservation/attribute --start">
<td class="start_date" tal:attributes="data-date start/ymd">
<span tal:condition="false: start/is_today" tal:content="start/ymd"/>
<span tal:condition="true: start/is_today">Heute</span>
</td>
<td class="start_time" tal:content="start/format '%H:%M'"/>
<td class="end_time" tal:define="end reservation/attribute --end" tal:content="end/format '%H:%M'"/>
<td class="user" tal:content="reservation/property --user"/>
<td>
<a class="cancel" tal:attributes="href string:${context/uri}/cancel/${reservation/id}" onclick="return confirm('Reservierung stornieren?');">stornieren</a>
</td>
</tr>
<tr tal:condition="true: reservation/property --info">
<td class="info" colspan="5" tal:content="reservation/property --info"/>
</tr>
</tbody>
</table>
<a class="new_reservation" tal:condition="false:reservation" tal:attributes="href string:${self/uri}/reserve">Neue Reservierung</a>
</div>
|
niner/CiderCMS
|
09853db260f7d63fadfbe1ce9c58a9557ead24fd
|
Support weekday restrictions in reservation
|
diff --git a/lib/CiderCMS/Controller/Custom/Reservation.pm b/lib/CiderCMS/Controller/Custom/Reservation.pm
index 6eb5a72..7a9c8f4 100644
--- a/lib/CiderCMS/Controller/Custom/Reservation.pm
+++ b/lib/CiderCMS/Controller/Custom/Reservation.pm
@@ -1,168 +1,185 @@
package CiderCMS::Controller::Custom::Reservation;
use strict;
use warnings;
use parent 'Catalyst::Controller';
use DateTime::Span;
use Hash::Merge qw(merge);
=head2 reserve
Reserve the displayed plane.
=cut
sub reserve : CiderCMS('reserve') {
my ( $self, $c ) = @_;
$c->detach('/user/login') unless $c->user;
my $params = $c->req->params;
my $save = delete $params->{save};
my $object = $c->stash->{context}->new_child(
attribute => 'reservations',
type => 'reservation',
);
my $errors = {};
if ($save) {
$errors = $object->validate($params);
unless ($errors) {
$params->{start_time} = sprintf '%02i:%02i', split /:/, $params->{start_time};
my $start = CiderCMS::Attribute::DateTime->parse_datetime(
"$params->{start_date} $params->{start_time}"
);
$errors = merge(
$self->check_time_limit($c, $start),
$self->check_end_limit($c, $params->{end}),
+ $self->check_weekdays_limit($c, $start),
$self->check_conflicts($c, $start, $params->{end}),
);
}
unless ($errors) {
$object->insert({data => $params});
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
$_ = join ', ', @$_ foreach values %$errors;
}
else {
$object->init_defaults;
}
$c->stash->{reservation} = 1;
$c->stash->{reserve} = 1;
my $content = $c->view('Petal')->render_template(
$c,
{
user => $c->user->get('name'),
%{ $c->stash },
%$params,
template => 'custom/reservation/reserve.zpt',
uri_cancel => $c->stash->{context}->uri . '/cancel',
errors => $errors,
},
);
$c->stash({
template => 'index.zpt',
content => $content,
});
return;
}
=head3 check_time_limit($c, $start)
=cut
sub check_time_limit {
my ($self, $c, $start) = @_;
my $time_limit = $c->stash->{context}->property('reservation_time_limit', undef);
return unless $time_limit;
my $limit = DateTime->now(time_zone => 'local')
->set_time_zone('floating')
->add(hours => $time_limit);
return {start => ['too close']} if $start->datetime lt $limit->datetime;
return;
}
=head3 check_end_limit($c, $end)
=cut
sub check_end_limit {
my ($self, $c, $end) = @_;
my $end_limit = $c->stash->{context}->property('reservation_end_limit', undef);
return unless $end_limit;
return {end => ['too late']} if $end gt $end_limit;
return;
}
+=head3 check_weekdays_limit($c, $end)
+
+=cut
+
+sub check_weekdays_limit {
+ my ($self, $c, $start) = @_;
+
+ my $weekdays_limit = $c->stash->{context}->property('reservation_weekdays_limit', undef);
+ return unless $weekdays_limit;
+ my %weekdays = map { $_ => 1 } split /,/, $weekdays_limit;
+
+ return {start => ['invalid weekday']} unless exists $weekdays{ $start->dow };
+
+ return;
+}
+
=head3 check_conflicts($c, $start)
=cut
sub check_conflicts {
my ($self, $c, $start, $end) = @_;
my $reservations = $c->stash->{context}->attribute('reservations');
my $new = create_datetime_span($start, $end);
foreach my $existing (@{ $reservations->filtered(cancelled_by => undef) }) {
my $existing = create_datetime_span(
$existing->attribute('start')->object,
$existing->property('end')
);
if ($new->intersects($existing)) {
return {start => ['conflicting existent reservation']};
}
}
return;
}
=head4 create_datetime_span($start, $end)
=cut
sub create_datetime_span {
my ($start, $end) = @_;
my ($end_h, $end_m) = split /:/, $end;
return DateTime::Span->from_datetimes(
start => $start,
end => $start->clone->set_hour($end_h)->set_minute($end_m)->subtract(seconds => 1)
);
}
=head2 cancel
Cancel the given reservation.
=cut
sub cancel : CiderCMS('cancel') Args(1) {
my ($self, $c, $id) = @_;
$c->detach('/user/login') unless $c->user;
my $context = $c->stash->{context};
my $reservation = $c->model('DB')->get_object($c, $id, $context->{level} + 1);
if ($reservation->{parent} == $context->{id}) {
$reservation->set_property(cancelled_by => $c->user->get('name'));
$reservation->update;
}
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
1;
diff --git a/t/custom_reservation.t b/t/custom_reservation.t
index f9c6b11..53a716d 100644
--- a/t/custom_reservation.t
+++ b/t/custom_reservation.t
@@ -1,335 +1,382 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
CiderCMS::Test->populate_types({
CiderCMS::Test->std_folder_type,
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'name',
data_type => 'String',
},
],
},
reservation => {
name => 'Reservation',
page_element => 1,
attributes => [
{
id => 'start',
data_type => 'DateTime',
mandatory => 1,
},
{
id => 'end',
data_type => 'Time',
mandatory => 1,
},
{
id => 'user',
data_type => 'String',
},
{
id => 'info',
data_type => 'String',
},
{
id => 'cancelled_by',
data_type => 'String',
},
],
},
airplane => {
name => 'Airplane',
page_element => 1,
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'reservations',
data_type => 'Object',
repetitive => 1,
},
{
id => 'reservation_time_limit',
data_type => 'Integer',
},
{
id => 'reservation_end_limit',
data_type => 'Time',
},
+ {
+ id => 'reservation_weekdays_limit',
+ data_type => 'String',
+ },
],
template => 'airplane.zpt'
},
});
my $root = $model->get_object($c, 1);
my $users = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Users' },
);
$users->create_child(
attribute => 'children',
type => 'user',
data => {
username => 'test',
name => 'test',
password => 'test',
},
);
my $airplanes = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Airplanes' },
);
my $dimona = $airplanes->create_child(
attribute => 'children',
type => 'airplane',
data => {
title => 'Dimona',
},
);
-$model->txn_do(sub {
+ok $model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->content_contains('Keine Reservierungen eingetragen.');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
$mech->content_lacks('Keine Reservierungen eingetragen.');
ok($mech->find_xpath(qq{//td[span="Heute"]}), "Today's reservation listed");
ok($mech->find_xpath(qq{//td[text()="test"]}), 'reserving user listed');
ok($mech->find_xpath(qq{//td[text()="Testflug"]}), 'Info listed');
$date->add(days => 1);
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
ok($mech->find_xpath(q{//td[span="Heute"]}), "Today's reservation still listed");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
$mech->get_ok(
$mech->find_xpath(q{//tr[td="Heute"]/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
is('' . $mech->find_xpath(q{//td[text()="Heute"]}), '', "Today's reservation gone");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/6/manage");
is($mech->value('cancelled_by'), 'test');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "conflicting existent reservation"]'),
'error message for conflict with existent reservation found'
);
$mech->get_ok("http://localhost/system/logout");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->get_ok(
$mech->find_xpath(q{//tr/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
not($mech->find_xpath('//span[text() = "conflicting existent reservation"]')),
'error message for conflict with existent reservation not found anymore'
);
$model->dbh->rollback;
});
-$model->txn_do(sub {
+ok $model->txn_do(sub {
# test error handling
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => 'invalid',
start_time => 'nonsense',
end => 'forget',
info => '',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $year = DateTime->now->add(years => 1)->year;
$mech->submit_form_ok({
with_fields => {
start_date => "6.12.$year",
start_time => '10:00',
end => '13:00',
info => '',
},
button => 'save',
});
ok(not($mech->find_xpath('//span[text() = "invalid"]')), 'valid date -> no error message');
$model->dbh->rollback;
});
-$model->txn_do(sub {
+ok $model->txn_do(sub {
# Update to test advance time limit
$dimona->set_property(reservation_time_limit => 24);
$dimona->update;
my $now = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->clone->add(hours => 1)->hms,
end => $now->clone->add(hours => 2)->hms,
info => 'too close',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "too close"]'), 'error message for too close date found');
$now = DateTime->now->add(days => 2)->add(hours => 4);
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->hms,
end => $now->clone->add(hours => 1)->hms,
info => 'too close',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too close"]'),
'',
'error message for too close date gone'
);
$model->dbh->rollback;
});
-$model->txn_do(sub {
+ok $model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
ok($mech->find_xpath(qq{//p[text()="Frei"]}), "No reservation active for now");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->subtract(hours => 1)->hms(':'),
end => $date->clone->add(hours => 2)->hour . ':00',
info => 'Testflug',
},
button => 'save',
});
is('' . $mech->find_xpath(qq{//p[text()="Frei"]}), '', "Reservation active for now");
$model->dbh->rollback;
});
-$model->txn_do(sub {
+ok $model->txn_do(sub {
# Update to test end time limit
$dimona->set_property(reservation_end_limit => '16:00');
$dimona->update;
my $now = DateTime->now->add(days => 1);
my $start = $now->clone->set_hour(15)->set_minute(0)->set_second(0);
my $end = $now->clone->set_hour(16)->set_minute(15)->set_second(0);
$mech->submit_form_ok({
with_fields => {
start_date => $start->ymd,
start_time => $start->hms,
end => $end->hms,
info => 'late test',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "too late"]'),
'error message for too late end time found',
);
$end->set_minute(0);
$mech->submit_form_ok({
with_fields => {
start_date => $start->ymd,
start_time => $start->hms,
end => $end->hms,
info => 'late test fixed',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too late"]'),
'',
'error message for too late date gone',
);
$model->dbh->rollback;
});
+ok $model->txn_do(sub {
+ # Update to test weekday limit
+ $dimona->set_property(reservation_weekdays_limit => '6,7');
+ $dimona->update;
+
+ # next Monday but at least a week away to avoid "too close"
+ my $monday = DateTime->now->clone->add(days => 7 + 8 - DateTime->now->dow);
+ my $start = $monday->set_hour(10)->set_minute(0)->set_second(0);
+ my $end = $start->clone->set_hour(12);
+ $mech->submit_form_ok({
+ with_fields => {
+ start_date => $start->ymd,
+ start_time => $start->hms,
+ end => $end->hms,
+ info => 'weekday test',
+ },
+ button => 'save',
+ });
+ ok(
+ $mech->find_xpath('//span[text() = "invalid weekday"]'),
+ 'error message for invalid weekday found',
+ );
+
+ $start->add(days => 5); # try again on Saturday
+ $end = $start->clone->set_hour(12);
+ $mech->submit_form_ok({
+ with_fields => {
+ start_date => $start->ymd,
+ start_time => $start->hms,
+ end => $end->hms,
+ info => 'weekday test fixed',
+ },
+ button => 'save',
+ });
+ is(
+ '' . $mech->find_xpath('//span[text() = "invalid weekday"]'),
+ '',
+ 'error message for invalid weekday gone',
+ );
+
+ $model->dbh->rollback;
+});
+
done_testing;
|
niner/CiderCMS
|
3c634147cf1e386dc5e87ab862b6ca94b30d8378
|
Support end time limit in reservation
|
diff --git a/lib/CiderCMS/Controller/Custom/Reservation.pm b/lib/CiderCMS/Controller/Custom/Reservation.pm
index db023f1..6eb5a72 100644
--- a/lib/CiderCMS/Controller/Custom/Reservation.pm
+++ b/lib/CiderCMS/Controller/Custom/Reservation.pm
@@ -1,152 +1,168 @@
package CiderCMS::Controller::Custom::Reservation;
use strict;
use warnings;
use parent 'Catalyst::Controller';
use DateTime::Span;
use Hash::Merge qw(merge);
=head2 reserve
Reserve the displayed plane.
=cut
sub reserve : CiderCMS('reserve') {
my ( $self, $c ) = @_;
$c->detach('/user/login') unless $c->user;
my $params = $c->req->params;
my $save = delete $params->{save};
my $object = $c->stash->{context}->new_child(
attribute => 'reservations',
type => 'reservation',
);
my $errors = {};
if ($save) {
$errors = $object->validate($params);
unless ($errors) {
$params->{start_time} = sprintf '%02i:%02i', split /:/, $params->{start_time};
my $start = CiderCMS::Attribute::DateTime->parse_datetime(
"$params->{start_date} $params->{start_time}"
);
$errors = merge(
$self->check_time_limit($c, $start),
+ $self->check_end_limit($c, $params->{end}),
$self->check_conflicts($c, $start, $params->{end}),
);
}
unless ($errors) {
$object->insert({data => $params});
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
$_ = join ', ', @$_ foreach values %$errors;
}
else {
$object->init_defaults;
}
$c->stash->{reservation} = 1;
$c->stash->{reserve} = 1;
my $content = $c->view('Petal')->render_template(
$c,
{
user => $c->user->get('name'),
%{ $c->stash },
%$params,
template => 'custom/reservation/reserve.zpt',
uri_cancel => $c->stash->{context}->uri . '/cancel',
errors => $errors,
},
);
$c->stash({
template => 'index.zpt',
content => $content,
});
return;
}
=head3 check_time_limit($c, $start)
=cut
sub check_time_limit {
my ($self, $c, $start) = @_;
my $time_limit = $c->stash->{context}->property('reservation_time_limit', undef);
return unless $time_limit;
my $limit = DateTime->now(time_zone => 'local')
->set_time_zone('floating')
->add(hours => $time_limit);
return {start => ['too close']} if $start->datetime lt $limit->datetime;
return;
}
+=head3 check_end_limit($c, $end)
+
+=cut
+
+sub check_end_limit {
+ my ($self, $c, $end) = @_;
+
+ my $end_limit = $c->stash->{context}->property('reservation_end_limit', undef);
+ return unless $end_limit;
+
+ return {end => ['too late']} if $end gt $end_limit;
+
+ return;
+}
+
=head3 check_conflicts($c, $start)
=cut
sub check_conflicts {
my ($self, $c, $start, $end) = @_;
my $reservations = $c->stash->{context}->attribute('reservations');
my $new = create_datetime_span($start, $end);
foreach my $existing (@{ $reservations->filtered(cancelled_by => undef) }) {
my $existing = create_datetime_span(
$existing->attribute('start')->object,
$existing->property('end')
);
if ($new->intersects($existing)) {
return {start => ['conflicting existent reservation']};
}
}
return;
}
=head4 create_datetime_span($start, $end)
=cut
sub create_datetime_span {
my ($start, $end) = @_;
my ($end_h, $end_m) = split /:/, $end;
return DateTime::Span->from_datetimes(
start => $start,
end => $start->clone->set_hour($end_h)->set_minute($end_m)->subtract(seconds => 1)
);
}
=head2 cancel
Cancel the given reservation.
=cut
sub cancel : CiderCMS('cancel') Args(1) {
my ($self, $c, $id) = @_;
$c->detach('/user/login') unless $c->user;
my $context = $c->stash->{context};
my $reservation = $c->model('DB')->get_object($c, $id, $context->{level} + 1);
if ($reservation->{parent} == $context->{id}) {
$reservation->set_property(cancelled_by => $c->user->get('name'));
$reservation->update;
}
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
1;
diff --git a/t/custom_reservation.t b/t/custom_reservation.t
index 2eee3a0..f9c6b11 100644
--- a/t/custom_reservation.t
+++ b/t/custom_reservation.t
@@ -1,290 +1,335 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
CiderCMS::Test->populate_types({
CiderCMS::Test->std_folder_type,
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'name',
data_type => 'String',
},
],
},
reservation => {
name => 'Reservation',
page_element => 1,
attributes => [
{
id => 'start',
data_type => 'DateTime',
mandatory => 1,
},
{
id => 'end',
data_type => 'Time',
mandatory => 1,
},
{
id => 'user',
data_type => 'String',
},
{
id => 'info',
data_type => 'String',
},
{
id => 'cancelled_by',
data_type => 'String',
},
],
},
airplane => {
name => 'Airplane',
page_element => 1,
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'reservations',
data_type => 'Object',
repetitive => 1,
},
{
id => 'reservation_time_limit',
data_type => 'Integer',
},
+ {
+ id => 'reservation_end_limit',
+ data_type => 'Time',
+ },
],
template => 'airplane.zpt'
},
});
my $root = $model->get_object($c, 1);
my $users = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Users' },
);
$users->create_child(
attribute => 'children',
type => 'user',
data => {
username => 'test',
name => 'test',
password => 'test',
},
);
my $airplanes = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Airplanes' },
);
my $dimona = $airplanes->create_child(
attribute => 'children',
type => 'airplane',
data => {
title => 'Dimona',
},
);
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->content_contains('Keine Reservierungen eingetragen.');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
$mech->content_lacks('Keine Reservierungen eingetragen.');
ok($mech->find_xpath(qq{//td[span="Heute"]}), "Today's reservation listed");
ok($mech->find_xpath(qq{//td[text()="test"]}), 'reserving user listed');
ok($mech->find_xpath(qq{//td[text()="Testflug"]}), 'Info listed');
$date->add(days => 1);
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
ok($mech->find_xpath(q{//td[span="Heute"]}), "Today's reservation still listed");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
$mech->get_ok(
$mech->find_xpath(q{//tr[td="Heute"]/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
is('' . $mech->find_xpath(q{//td[text()="Heute"]}), '', "Today's reservation gone");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/6/manage");
is($mech->value('cancelled_by'), 'test');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "conflicting existent reservation"]'),
'error message for conflict with existent reservation found'
);
$mech->get_ok("http://localhost/system/logout");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->get_ok(
$mech->find_xpath(q{//tr/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
not($mech->find_xpath('//span[text() = "conflicting existent reservation"]')),
'error message for conflict with existent reservation not found anymore'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
# test error handling
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => 'invalid',
start_time => 'nonsense',
end => 'forget',
info => '',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $year = DateTime->now->add(years => 1)->year;
$mech->submit_form_ok({
with_fields => {
start_date => "6.12.$year",
start_time => '10:00',
end => '13:00',
info => '',
},
button => 'save',
});
ok(not($mech->find_xpath('//span[text() = "invalid"]')), 'valid date -> no error message');
$model->dbh->rollback;
});
$model->txn_do(sub {
# Update to test advance time limit
$dimona->set_property(reservation_time_limit => 24);
$dimona->update;
my $now = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->clone->add(hours => 1)->hms,
end => $now->clone->add(hours => 2)->hms,
info => 'too close',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "too close"]'), 'error message for too close date found');
$now = DateTime->now->add(days => 2)->add(hours => 4);
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->hms,
end => $now->clone->add(hours => 1)->hms,
info => 'too close',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too close"]'),
'',
'error message for too close date gone'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
ok($mech->find_xpath(qq{//p[text()="Frei"]}), "No reservation active for now");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->subtract(hours => 1)->hms(':'),
end => $date->clone->add(hours => 2)->hour . ':00',
info => 'Testflug',
},
button => 'save',
});
is('' . $mech->find_xpath(qq{//p[text()="Frei"]}), '', "Reservation active for now");
$model->dbh->rollback;
});
+$model->txn_do(sub {
+ # Update to test end time limit
+ $dimona->set_property(reservation_end_limit => '16:00');
+ $dimona->update;
+
+ my $now = DateTime->now->add(days => 1);
+ my $start = $now->clone->set_hour(15)->set_minute(0)->set_second(0);
+ my $end = $now->clone->set_hour(16)->set_minute(15)->set_second(0);
+ $mech->submit_form_ok({
+ with_fields => {
+ start_date => $start->ymd,
+ start_time => $start->hms,
+ end => $end->hms,
+ info => 'late test',
+ },
+ button => 'save',
+ });
+ ok(
+ $mech->find_xpath('//span[text() = "too late"]'),
+ 'error message for too late end time found',
+ );
+
+ $end->set_minute(0);
+ $mech->submit_form_ok({
+ with_fields => {
+ start_date => $start->ymd,
+ start_time => $start->hms,
+ end => $end->hms,
+ info => 'late test fixed',
+ },
+ button => 'save',
+ });
+ is(
+ '' . $mech->find_xpath('//span[text() = "too late"]'),
+ '',
+ 'error message for too late date gone',
+ );
+
+ $model->dbh->rollback;
+});
+
done_testing;
|
niner/CiderCMS
|
894206124adce5e86631f625ec3876b300ae7a16
|
Port t/07controller_Content-Management.t to CiderCMS::Test
|
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index 5218bbb..1ec15ef 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,246 +1,247 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
=head2 context
Returns a $c object for tests.
=cut
sub context {
my ($self) = @_;
require Catalyst::Test;
Catalyst::Test->import('CiderCMS');
my ($res, $c) = ctx_request('/system/create');
delete $c->stash->{$_} foreach keys %{ $c->stash };
return $c;
}
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
$ENV{ CIDERCMS_CONFIG_LOCAL_SUFFIX } = 'test';
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
my $c = $self->context;
my $model = $c->model('DB');
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
=head3 std_folder_type
=cut
sub std_folder_type {
return folder => {
name => 'Folder',
attributes => [
{
id => 'title',
data_type => 'Title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
mandatory => 0,
repetitive => 1,
},
],
};
}
=head3 std_textfield_type
=cut
sub std_textfield_type {
return textfield => {
name => 'Textfield',
page_element => 1,
attributes => [
{
id => 'text',
data_type => 'Text',
mandatory => 1,
},
],
+ template => 'textfield.zpt',
};
}
sub write_template {
my ($self, $file, $contents) = @_;
write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
}
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
undef $mech;
}
1;
diff --git a/t/07controller_Content-Management.t b/t/controller_Content-Management.t
similarity index 71%
rename from t/07controller_Content-Management.t
rename to t/controller_Content-Management.t
index 9ffed17..a1b6bb5 100644
--- a/t/07controller_Content-Management.t
+++ b/t/controller_Content-Management.t
@@ -1,158 +1,179 @@
use strict;
use warnings;
use Test::More;
use FindBin qw($Bin);
use utf8;
-eval "use Test::WWW::Mechanize::Catalyst 'CiderCMS'";
-plan $@
- ? ( skip_all => 'Test::WWW::Mechanize::Catalyst required' )
- : ( tests => 49 );
-
-ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+
+CiderCMS::Test->populate_types({
+ CiderCMS::Test->std_folder_type,
+ CiderCMS::Test->std_textfield_type,
+ image => {
+ name => 'Image',
+ page_element => 1,
+ attributes => [
+ {
+ id => 'img',
+ name => 'Image file',
+ data_type => 'Image',
+ mandatory => 1,
+ },
+ {
+ id => 'title',
+ name => 'Title',
+ data_type => 'String',
+ mandatory => 0,
+ },
+ ],
+ template => 'image.zpt',
+ },
+});
-$mech->get_ok( 'http://localhost/test.example/manage' );
+$mech->get_ok("http://localhost/$instance/manage");
-# Create a new textarea
-$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=textarea} }, 'Add a textarea');
+# Create a new textfield
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=textfield} }, 'Add a textfield');
$mech->submit_form_ok({
with_fields => {
text => 'Foo qux baz!',
},
button => 'save',
});
-$mech->content_like(qr/Foo qux baz!/, 'New textarea present');
+$mech->content_like(qr/Foo qux baz!/, 'New textfield present');
-# Edit the textarea
-$mech->follow_link_ok({ url_regex => qr{2/manage} }, 'Edit textarea');
+# Edit the textfield
+$mech->follow_link_ok({ url_regex => qr{2/manage} }, 'Edit textfield');
$mech->submit_form_ok({
with_fields => {
text => 'Foo bar baz!',
},
button => 'save',
});
-$mech->content_like(qr/Foo bar baz!/, 'New textarea content');
+$mech->content_like(qr/Foo bar baz!/, 'New textfield content');
-# Add a second textarea and delete it
-$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=textarea} }, 'Add a second textarea');
+# Add a second textfield and delete it
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=textfield} }, 'Add a second textfield');
$mech->submit_form_ok({
with_fields => {
text => 'Delete me!',
} ,
button => 'save',
});
-$mech->content_like(qr/Delete me!/, 'New textarea content');
-$mech->follow_link_ok({ url_regex => qr{manage_delete\b.*\bid=3} }, 'Delete new textarea');
+$mech->content_like(qr/Delete me!/, 'New textfield content');
+$mech->follow_link_ok({ url_regex => qr{manage_delete\b.*\bid=3} }, 'Delete new textfield');
$mech->content_unlike(qr/Delete me!/, 'Textarea gone');
# Try some image
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=image} }, 'Add an image');
$mech->submit_form_ok({
with_fields => {
img => "$Bin/../root/static/images/catalyst_logo.png",
} ,
button => 'save',
});
my $image = $mech->find_image(url_regex => qr{catalyst_logo});
$mech->get_ok($image->url);
$mech->back;
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Folder 1',
},
button => 'save',
});
$mech->title_is('Edit Folder', 'Editing folder');
ok($mech->uri->path =~ m!/folder_1/!, 'dcid set correctly');
-# Add a textarea to our folder
-$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=textarea} }, 'Add a textarea');
+# Add a textfield to our folder
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=textfield} }, 'Add a textfield');
$mech->submit_form_ok({
with_fields => {
text => 'Page 1',
},
button => 'save',
});
$mech->title_is('Edit Folder', 'Editing folder again');
-$mech->follow_link_ok({ url_regex => qr(test.example/manage) }, 'Back to top level');
+$mech->follow_link_ok({ url_regex => qr($instance/manage) }, 'Back to top level');
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Folder 0',
},
button => 'save',
});
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Folder 0.1',
},
button => 'save',
});
-$mech->follow_link_ok({ url_regex => qr(test.example/manage) }, 'Back to top level');
+$mech->follow_link_ok({ url_regex => qr($instance/manage) }, 'Back to top level');
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder}, n => 3 }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Földer 2', # try some umlaut
},
button => 'save',
});
$mech->submit_form_ok({
with_fields => {
title => 'Folder 2', # correct it
},
button => 'save',
});
ok($mech->value('title') eq 'Folder 2', 'Title updated');
-$mech->follow_link_ok({ url_regex => qr(test.example/manage) }, 'Back to top level');
+$mech->follow_link_ok({ url_regex => qr($instance/manage) }, 'Back to top level');
$mech->content_like(qr((?s)folder_0.*folder_1.*folder_2), 'Folders in correct order');
SKIP: {
eval { require Test::XPath; };
skip 'Test::XPath not installed', 14 if $@;
my $xpath = Test::XPath->new( xml => $mech->content, is_html => 1 );
$xpath->like('//div[@class="child folder"][3]/@id', qr/\A child_(\d+) \z/x);
my $xpc = $xpath->xpc;
my $child_id = $xpc->findvalue('//div[@class="child folder"][3]/@id');
$mech->follow_link_ok({ url_regex => qr(folder_1/manage) }, 'Go to folder 1');
$xpath = Test::XPath->new( xml => $mech->content, is_html => 1 );
$xpath->ok('id("breadcrumbs")', 'Bread crumbs found');
$xpath->ok('id("breadcrumbs")//a', 'Links in bread crumbs');
$xpath->ok('id("breadcrumbs")//a[contains(text(), "Folder")]', 'Folder 1 title in breadcrumbs');
$xpath->ok('id("breadcrumbs")//a[contains(@href, "folder_1")]', 'Folder 1 href in breadcrumbs');
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a subfolder');
$mech->submit_form_ok({
with_fields => {
title => 'Folder 3',
},
button => 'save',
});
$mech->follow_link_ok({ url_regex => qr(folder_1/manage) }, 'Back to folder_1');
$xpath = Test::XPath->new( xml => $mech->content, is_html => 1 );
$xpc = $xpath->xpc;
my $folder_3_id = $xpc->findvalue('//div[@class="child folder"][1]/@id');
my ($id) = $child_id =~ /child_(\d+)/;
($folder_3_id) = $folder_3_id =~ /child_(\d+)/;
$mech->get_ok($mech->uri . "_paste?attribute=children;id=$id;after=$folder_3_id");
$mech->content_like(qr((?s)folder_3.*folder_2), 'Folders in correct order');
$mech->follow_link_ok({ url_regex => qr{folder_2/manage} }, 'Folder 2 works');
$mech->back;
- # now move the textarea to folder_3 to set up for the content tests
+ # now move the textfield to folder_3 to set up for the content tests
$xpath = Test::XPath->new( xml => $mech->content, is_html => 1 );
$xpc = $xpath->xpc;
- my $textarea_id = $xpc->findvalue('//div[@class="child textarea"][1]/@id');
- ($textarea_id) = $textarea_id =~ /child_(\d+)/;
+ my $textfield_id = $xpc->findvalue('//div[@class="child textfield"][1]/@id');
+ ($textfield_id) = $textfield_id =~ /child_(\d+)/;
$mech->follow_link_ok({ url_regex => qr{folder_3/manage} });
- $mech->get_ok($mech->uri . "_paste?attribute=children;id=$textarea_id");
+ $mech->get_ok($mech->uri . "_paste?attribute=children;id=$textfield_id");
}
+
+done_testing;
|
niner/CiderCMS
|
8045c611f0c3e2b956eaa6ad4ce072acbe4d909b
|
Port t/06controller_Root.t to CiderCMS::Test
|
diff --git a/t/06controller_Root.t b/t/06controller_Root.t
deleted file mode 100644
index 531a2d4..0000000
--- a/t/06controller_Root.t
+++ /dev/null
@@ -1,14 +0,0 @@
-use strict;
-use warnings;
-use Test::More;
-
-eval "use Test::WWW::Mechanize::Catalyst 'CiderCMS'";
-plan $@
- ? ( skip_all => 'Test::WWW::Mechanize::Catalyst required' )
- : ( tests => 3 );
-
-ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
-
-is($mech->get('http://localhost/test.example/not_existing')->code, 404, 'test the 404 response');
-
-$mech->get_ok('http://localhost/test.example/manage');
diff --git a/t/controller_Root.t b/t/controller_Root.t
new file mode 100644
index 0000000..193ba6e
--- /dev/null
+++ b/t/controller_Root.t
@@ -0,0 +1,11 @@
+use strict;
+use warnings;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+
+is($mech->get("http://localhost/$instance/not_existing")->code, 404, 'test the 404 response');
+
+$mech->get_ok("http://localhost/$instance/manage");
+
+done_testing;
|
niner/CiderCMS
|
7e38131ae1bbc8dcd042f9a6eecf2dd787b135cd
|
Port t/12Attribute-Recipient.t to CiderCMS::Test
|
diff --git a/t/12Attribute-Recipient.t b/t/12Attribute-Recipient.t
deleted file mode 100644
index 67d4877..0000000
--- a/t/12Attribute-Recipient.t
+++ /dev/null
@@ -1,73 +0,0 @@
-use strict;
-use warnings;
-use Test::More;
-use FindBin qw($Bin);
-use MIME::Lite;
-use utf8;
-
-eval "use Test::WWW::Mechanize::Catalyst 'CiderCMS'";
-plan $@
- ? ( skip_all => 'Test::WWW::Mechanize::Catalyst required' )
- : ( tests => 13 );
-
-my $sent_mail;
-MIME::Lite->send(sub => sub {
- my ($self) = @_;
-
- $sent_mail = $self->as_string;
-});
-
-ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
-
-$mech->get_ok( 'http://localhost/test.example/system/types' );
-
-# add a Contact type to test Recipient attributes
-$mech->submit_form_ok({
- with_fields => {
- id => 'contact',
- name => 'Contact form',
- page_element => 1,
- },
- button => 'save',
-}, 'Create Contact form type');
-$mech->submit_form_ok({
- with_fields => {
- id => 'recipient',
- name => 'Recipient',
- data_type => 'Recipient',
- mandatory => 1,
- },
-}, 'Add recipient attribute');
-$mech->submit_form_ok({
- with_fields => {
- id => 'subject',
- name => 'Subject',
- data_type => 'String',
- mandatory => 0,
- },
-}, 'Add subject attribute');
-
-$mech->get_ok( 'http://localhost/test.example/manage' );
-
-$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=contact} }, 'Add a form');
-$mech->submit_form_ok({
- with_fields => {
- recipient => 'nine',
- subject => 'Testform',
- },
- button => 'save',
-});
-
-$mech->get_ok( 'http://localhost/test.example/index.html' );
-
-$mech->submit_form_ok({
- with_fields => {
- foo => 'Foo',
- bar => "Bar\nBaz",
- },
- button => 'send',
-});
-
-ok($sent_mail =~ /Subject: Testform/, 'Subject of sent mail correct');
-ok($sent_mail =~ /To: nine/, 'Recipient of sent mail correct');
-like($sent_mail, qr/\n\nbar: Bar\r?\nBaz\nfoo: Foo/s, 'Text of sent mail correct');
diff --git a/t/Attribute-Recipient.t b/t/Attribute-Recipient.t
new file mode 100644
index 0000000..e8eb187
--- /dev/null
+++ b/t/Attribute-Recipient.t
@@ -0,0 +1,61 @@
+use strict;
+use warnings;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+use MIME::Lite;
+use utf8;
+
+my $sent_mail;
+MIME::Lite->send(sub => sub {
+ my ($self) = @_;
+
+ $sent_mail = $self->as_string;
+});
+
+# add a Contact type to test Recipient attributes
+CiderCMS::Test->populate_types({
+ contact => {
+ name => 'Contact form',
+ attributes => [
+ {
+ id => 'recipient',
+ mandatory => 1,
+ },
+ {
+ id => 'subject',
+ data_type => 'String',
+ mandatory => 1,
+ },
+ ],
+ page_element => 1,
+ template => 'contact.zpt',
+ },
+});
+
+$mech->get_ok("http://localhost/$instance/manage");
+
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=contact} }, 'Add a form');
+$mech->submit_form_ok({
+ with_fields => {
+ recipient => 'nine',
+ subject => 'Testform',
+ },
+ button => 'save',
+});
+
+$mech->get_ok("http://localhost/$instance/index.html");
+
+$mech->submit_form_ok({
+ with_fields => {
+ foo => 'Foo',
+ bar => "Bar\nBaz",
+ },
+ button => 'send',
+});
+
+ok($sent_mail =~ /Subject: Testform/, 'Subject of sent mail correct');
+ok($sent_mail =~ /To: nine/, 'Recipient of sent mail correct');
+like($sent_mail, qr/\n\nbar: Bar\r?\nBaz\nfoo: Foo/s, 'Text of sent mail correct');
+
+done_testing;
|
niner/CiderCMS
|
3d0bfb378f4160a71ce07457506b2fd069af8d70
|
Make clean_sort_ids.pl more agressive
|
diff --git a/script/clean_sort_ids.pl b/script/clean_sort_ids.pl
index f71fc43..0108355 100644
--- a/script/clean_sort_ids.pl
+++ b/script/clean_sort_ids.pl
@@ -1,43 +1,47 @@
use 5.14.0;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../lib";
use CiderCMS::Test;
my $c = CiderCMS::Test::context;
my $model = $c->model('DB');
my $dbh = $model->dbh;
foreach my $instance (@{ $model->instances }) {
say $instance;
$model->txn_do(sub {
$dbh->do("set search_path=?", undef, $instance);
my $sys_object = $dbh->quote_identifier(undef, $instance, 'sys_object');
my $objects = $dbh->selectall_arrayref(
"select * from $sys_object where parent is not null order by parent, parent_attr, sort_id",
{Slice => {}},
);
my $parent = 0;
my $parent_attr = '';
my $sort_id;
foreach my $object (@$objects) {
if ($parent != $object->{parent} or $parent_attr ne $object->{parent_attr}) {
$sort_id = 0;
$parent = $object->{parent};
$parent_attr = $object->{parent_attr};
- }
- $sort_id++;
- if ($object->{sort_id} != $sort_id) {
- say "$object->{parent}/$object->{parent_attr}: $object->{sort_id} => $sort_id";
$dbh->do(
- "update $sys_object set sort_id = ? where id = ?",
+ "update $sys_object set sort_id = -sort_id where parent = ? and parent_attr = ?",
undef,
- $sort_id,
- $object->{id},
+ $parent,
+ $parent_attr,
);
}
+ $sort_id++;
+ say "$object->{parent}/$object->{parent_attr}: $object->{sort_id} => $sort_id";
+ $dbh->do(
+ "update $sys_object set sort_id = ? where id = ?",
+ undef,
+ $sort_id,
+ $object->{id},
+ );
}
});
}
|
niner/CiderCMS
|
820d60e5187bf3a0bfd9886a04ac0b5e21522a91
|
Replace CIDERCMS_INSTANCE ENV variable by HTTP header
|
diff --git a/lib/CiderCMS.pm b/lib/CiderCMS.pm
index dd7788c..c47b910 100644
--- a/lib/CiderCMS.pm
+++ b/lib/CiderCMS.pm
@@ -1,187 +1,180 @@
package CiderCMS;
use strict;
use warnings;
use Catalyst::Runtime 5.80;
use Catalyst::DispatchType::CiderCMS;
# Set flags and add plugins for the application
#
# ConfigLoader: will load the configuration from a Config::General file in the
# application's home directory
# Static::Simple: will serve static files from the application's root
# directory
use parent qw/Catalyst/;
use Catalyst qw/
ConfigLoader
Static::Simple
FormValidator
Authentication
Session
Session::State::Cookie
Session::Store::FastMmap
/;
our $VERSION = '0.01';
# Configure the application.
#
# Note that settings in cidercms.conf (or other external
# configuration file that you set up manually) take precedence
# over this when using ConfigLoader. Thus configuration
# details given here can function as a default configuration,
# with an external configuration file acting as an override for
# local deployment.
__PACKAGE__->config(
name => 'CiderCMS',
encoding => 'UTF-8',
);
# Start the application
__PACKAGE__->setup();
=head1 NAME
CiderCMS - Catalyst based application
=head1 SYNOPSIS
script/cidercms_server.pl
=head1 DESCRIPTION
CiderCMS is a very flexible CMS.
=head1 METHODS
=head2 prepare_path
-Checks for an CIDERCMS_INSTANCE environment variable and prepends it to the path if present.
+Checks for an cidercms_instance HTTP header and prepends it to the path if present.
=cut
sub prepare_path {
my ($self, @args) = @_;
$self->maybe::next::method(@args);
my $uri_raw = $self->request->uri->clone;
- if (my $instance = $ENV{CIDERCMS_INSTANCE}) {
+ if (my $instance = $self->request->header('cidercms_instance')) {
my $uri = $uri_raw->clone;
my $path = $instance . $uri->path;
$uri->path($path);
$self->request->path($path);
$uri->path_query('');
$uri->fragment(undef);
$self->stash({
uri_instance => $uri,
uri_static => "$uri/static",
uri_raw => $uri_raw,
});
}
else {
$self->stash->{uri_raw} = $uri_raw;
}
return;
}
-if ($ENV{CIDERCMS_INSTANCE}) {
- __PACKAGE__->config->{static}{include_path} = [
- __PACKAGE__->config->{root} . '/instances/',
- __PACKAGE__->config->{root},
- ];
-}
-
=head2 uri_for_instance(@path)
Creates an URI relative to the current instance's root
=cut
sub uri_for_instance {
my ($self, @path) = @_;
return ($self->stash->{uri_instance} ||= $self->uri_for('/') . $self->stash->{instance}) . (@path ? join '/', '', @path : '');
}
=head2 uri_static_for_instance()
Returns an URI for static files for this instance
=cut
sub uri_static_for_instance {
my ($self, @path) = @_;
return join '/', ($self->stash->{uri_static} or $self->uri_for('/') . (join '/', 'instances', $self->stash->{instance}, 'static')), @path;
}
=head2 fs_path_for_instance()
Returns a file system path for the current instance's root
=cut
sub fs_path_for_instance {
my ($self) = @_;
return $self->config->{root} . '/instances/' . $self->stash->{instance} . '/static';
}
=head2 register_management_action
Controllers may register subroutines returning additional actions for the management interface dynamically.
For example:
CiderCMS->register_management_action(__PACKAGE__, sub {
my ($self, $c) = @_;
return {title => 'Foo', uri => $c->uri_for('foo')}, { ... };
});
=cut
my %management_actions;
sub register_management_action {
my ($self, $package, $action_creator) = @_;
$management_actions{$package} = $action_creator;
return;
}
=head2 management_actions
Returns the registered management actions
=cut
sub management_actions {
my ($self) = @_;
return \%management_actions;
}
=head1 SEE ALSO
L<CiderCMS::Controller::Root>, L<Catalyst>
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Controller/Root.pm b/lib/CiderCMS/Controller/Root.pm
index a35a09a..f8ffd54 100644
--- a/lib/CiderCMS/Controller/Root.pm
+++ b/lib/CiderCMS/Controller/Root.pm
@@ -1,96 +1,108 @@
package CiderCMS::Controller::Root;
use strict;
use warnings;
use parent 'Catalyst::Controller';
#
# Sets the actions in this controller to be registered with no prefix
# so they function identically to actions created in MyApp.pm
#
__PACKAGE__->config->{namespace} = '';
=head1 NAME
CiderCMS::Controller::Root - Root Controller for CiderCMS
=head1 DESCRIPTION
[enter your description here]
=head1 METHODS
=head2 not_found
Just throw a 404.
=cut
-sub not_found :Path {
+sub not_found :Private {
my ( $self, $c ) = @_;
my $dispatch_error = $c->stash->{dispatch_error} // 'Page not found';
$dispatch_error =~ s/\n[^\n]*\z//xm;
$c->response->body($dispatch_error);
$c->response->status(404);
return;
}
+sub default : Path {
+ my ($self, $c) = @_;
+
+ my $path = $c->config->{root} . '/instances/' . $c->req->path;
+
+ if (-e $path and -f $path and -s $path) {
+ return $c->serve_static_file($path);
+ }
+
+ $c->forward($c->controller->action_for('not_found'));
+}
+
=head2 render
Attempt to render a view, if needed.
=cut
sub render : ActionClass('RenderView') {
return;
}
=head2 end
Render a view or display a custom error page in case of an error happened.
=cut
sub end : Private {
my ( $self, $c ) = @_;
$c->forward('render');
if (@{ $c->error }) {
$c->res->status(500);
warn join "\n", @{ $c->error };
# avoid disclosure of the application's path
my @errors = @{ $c->error };
my $home = $c->config->{home};
s!$home/!!g foreach @errors;
$c->stash({
template => 'error.zpt',
errors => \@errors,
});
$c->forward('render');
$c->clear_errors;
}
return;
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index 995108e..5218bbb 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,245 +1,246 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
=head2 context
Returns a $c object for tests.
=cut
sub context {
my ($self) = @_;
require Catalyst::Test;
Catalyst::Test->import('CiderCMS');
my ($res, $c) = ctx_request('/system/create');
delete $c->stash->{$_} foreach keys %{ $c->stash };
return $c;
}
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
$ENV{ CIDERCMS_CONFIG_LOCAL_SUFFIX } = 'test';
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
my $c = $self->context;
my $model = $c->model('DB');
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
=head3 std_folder_type
=cut
sub std_folder_type {
return folder => {
name => 'Folder',
attributes => [
{
id => 'title',
data_type => 'Title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
mandatory => 0,
repetitive => 1,
},
],
};
}
=head3 std_textfield_type
=cut
sub std_textfield_type {
return textfield => {
- name => 'Textfield',
+ name => 'Textfield',
+ page_element => 1,
attributes => [
{
id => 'text',
data_type => 'Text',
mandatory => 1,
},
],
};
}
sub write_template {
my ($self, $file, $contents) = @_;
write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
}
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
undef $mech;
}
1;
diff --git a/lib/CiderCMS/View/Petal.pm b/lib/CiderCMS/View/Petal.pm
index 1e8306a..b008de2 100644
--- a/lib/CiderCMS/View/Petal.pm
+++ b/lib/CiderCMS/View/Petal.pm
@@ -1,88 +1,96 @@
package CiderCMS::View::Petal;
use strict;
use warnings;
use base 'Catalyst::View::Petal';
use Petal::Utils qw( :all Reverse );
=head1 NAME
CiderCMS::View::Petal - Petal View Component
=head1 SYNOPSIS
Catalyst View.
=head1 DESCRIPTION
Very nice component.
=head1 METHODS
=head2 process
=cut
sub process {
my ($self, $c) = @_;
my $root = $c->config->{root};
if (my $instance = $c->stash->{instance}) {
$self->config(base_dir => ["$root/instances/$instance/templates", "$root/templates"]);
$c->stash->{uri_static} ||= $c->uri_static_for_instance();
}
else {
$self->config(base_dir => "$root/templates");
}
$c->stash({
uri_root => $c->uri_for('/'),
- uri_sys_static => $c->uri_for($ENV{CIDERCMS_INSTANCE} ? '/sys_static' : '/static'),
+ uri_sys_static => $c->uri_for(
+ $c->request->header('cidercms_instance')
+ ? '/sys_static'
+ : '/static',
+ ),
});
return $self->SUPER::process($c);
}
=head2 render_template
Renders a Petal template and returns the result as string.
=cut
sub render_template {
my ($self, $c, $stash) = @_;
my $root = $c->config->{root};
my $instance = $c->stash->{instance};
my $template = Petal->new(
%{ $self->config },
base_dir => ["$root/instances/$instance/templates", "$root/templates"],
file => $stash->{template},
);
return $template->process({
c => $c,
uri_static => ($c->stash->{uri_static} or $c->uri_static_for_instance()),
- uri_sys_static => $c->uri_for($ENV{CIDERCMS_INSTANCE} ? '/sys_static' : '/static'),
+ uri_sys_static => $c->uri_for(
+ $c->request->header('cidercms_instance')
+ ? '/sys_static'
+ : '/static',
+ ),
%$stash,
});
}
__PACKAGE__->config(input => 'XHTML', output => 'XHTML');
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software . You can redistribute it and/or modify it under
the same terms as perl itself.
=cut
1;
diff --git a/t/controller_Content_env_instance.t b/t/controller_Content_env_instance.t
index dce3604..e54f162 100644
--- a/t/controller_Content_env_instance.t
+++ b/t/controller_Content_env_instance.t
@@ -1,55 +1,113 @@
use strict;
use warnings;
+use utf8;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
+
use FindBin qw($Bin);
use File::Temp qw(tempfile);
use Image::Imlib2;
-BEGIN {
- # test INSTANCE environment var
- $ENV{CIDERCMS_INSTANCE} = 'test.example';
-}
+CiderCMS::Test->populate_types({
+ CiderCMS::Test->std_folder_type,
+ CiderCMS::Test->std_textfield_type,
+});
+
+CiderCMS::Test->populate_types({
+ image => {
+ name => 'Image',
+ page_element => 1,
+ attributes => [
+ {
+ id => 'img',
+ data_type => 'Image',
+ mandatory => 1,
+ },
+ ],
+ },
+});
+
+system ('/bin/cp', '-r', "$Bin/test.example/templates", "$Bin/test.example/static", "$Bin/../root/instances/$instance/");
-eval "use Test::WWW::Mechanize::Catalyst 'CiderCMS'";
-plan $@
- ? ( skip_all => 'Test::WWW::Mechanize::Catalyst required' )
- : ( tests => 14 );
+my $root = $model->get_object($c, 1);
+ $root->create_child(
+ attribute => 'children',
+ type => 'textfield',
+ data => {
+ text => 'Foo bar baz!',
+ },
+ );
+ my $folder = $root->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Folder 1' },
+ );
+ my $sub_folder = $folder->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Folder 2' },
+ );
+ my $sub_sub_folder = $sub_folder->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Folder 3' },
+ );
+ $sub_sub_folder->create_child(
+ attribute => 'children',
+ type => 'textfield',
+ data => {
+ text => 'Foo bar baz!',
+ },
+ );
-ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
+$mech->add_header(cidercms_instance => $instance);
$mech->get_ok('http://localhost/index.html');
-$mech->title_is('Testsite', 'Title correct');
+$mech->title_is('test instance', 'Title correct');
+
$mech->content_like(qr/Foo bar baz!/, 'Textarea present');
-my $styles = $mech->find_link(url_regex => qr{styles.css});
-$mech->links_ok([ $styles ]);
+my $styles = $mech->follow_link_ok({url_regex => qr{styles.css}});
$mech->get_ok('http://localhost/', 'short URI without index.html works');
# images work
+$mech->get_ok("http://localhost/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=image} }, 'Add an image');
+
+$mech->submit_form_ok({
+ with_fields => {
+ img => "$Bin/../root/static/images/catalyst_logo.png",
+ },
+ button => 'save',
+});
+
+$mech->get_ok('http://localhost/index.html');
my $img = $mech->find_image(url_regex => qr{catalyst_logo});
$mech->get_ok($img->url);
my ($fh, $filename) = tempfile();
$mech->save_content($filename);
my $image = Image::Imlib2->load($filename);
ok($image->width <= 80, 'thumbnail width <= 80');
ok($image->height <= 60, 'thumbnail height <= 60');
$mech->back;
$mech->get_ok('http://localhost/', 'new layout works');
$mech->follow_link_ok({ url_regex => qr(folder_1) });
-$mech->title_is('Folder 1', 'We got to the first subfolder with page elements');
+$mech->title_is('Folder 3', 'We got to the first subfolder with page elements');
SKIP: {
eval { require Test::XPath; };
skip 'Test::XPath not installed', 2 if $@;
my $xpath = Test::XPath->new( xml => $mech->content, is_html => 1 );
$xpath->ok('id("subnav")', 'subnav found');
$mech->follow_link_ok({ url_regex => qr(folder_2) });
}
+done_testing;
diff --git a/t/test.example/static/css/styles.css b/t/test.example/static/css/styles.css
index e69de29..25fa51c 100644
--- a/t/test.example/static/css/styles.css
+++ b/t/test.example/static/css/styles.css
@@ -0,0 +1,2 @@
+body {
+}
diff --git a/t/test.example/templates/index.zpt b/t/test.example/templates/index.zpt
index 0d8cede..12bdc47 100644
--- a/t/test.example/templates/index.zpt
+++ b/t/test.example/templates/index.zpt
@@ -1,32 +1,34 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
xml:lang="en"
lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
xmlns:i18n="http://xml.zope.org/namespaces/i18n"
i18n:domain="CiderCMS">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title tal:content="context/property --title --CiderCMS">CiderCMS</title>
<link rel="stylesheet" tal:attributes="href string:${uri_static}/css/styles.css" />
</head>
<body>
<div id="page">
<ul id="nav">
<li tal:repeat="child site/children"><a tal:attributes="href child/uri_index" tal:define="child_type child/type/name" tal:content="child/property --title child_type"/></li>
</ul>
- <ul id="subnav" tal:define="root context/parent_by_level '1'; children root/attribute --children; pages children/pages" tal:condition="true: pages">
- <li tal:repeat="child pages"><a tal:attributes="href child/uri_index" tal:define="child_type child/type/name" tal:content="child/property --title child_type"/></li>
- </ul>
+ <div tal:define="root context/parent_by_level '1'" tal:condition="true: root" tal:omit-tag="">
+ <ul id="subnav" tal:define="root context/parent_by_level '1'; children root/attribute --children; pages children/pages" tal:condition="true: pages">
+ <li tal:repeat="child pages"><a tal:attributes="href child/uri_index" tal:define="child_type child/type/name" tal:content="child/property --title child_type"/></li>
+ </ul>
+ </div>
<div id="get_object" tal:define="obj context/object_by_id '4'" tal:content="structure obj/property --text ''"/>
<div id="content" tal:content="structure content"/>
</div>
</body>
</html>
|
niner/CiderCMS
|
a23444f77dc0feab551055f0384154a0b36e6bf6
|
Actually survive exceptions in txn_do
|
diff --git a/lib/CiderCMS/Model/DB.pm b/lib/CiderCMS/Model/DB.pm
index 4b07ea9..0d9a280 100644
--- a/lib/CiderCMS/Model/DB.pm
+++ b/lib/CiderCMS/Model/DB.pm
@@ -34,543 +34,543 @@ CiderCMS::Model::DB - DBI Model Class
Creates a new instance including schema and instance directory
=cut
sub create_instance {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
my $instance_path = $c->config->{root} . '/instances/' . $data->{id};
mkdir "$instance_path$_" foreach '', qw( /static /templates /templates/layout /templates/content );
$dbh->do(qq(create schema "$data->{id}")) or croak qq(could not create schema "$data->{id}");
$dbh->do(qq(set search_path="$data->{id}",public)) or croak qq(could not set search path "$data->{id}",public!?);
$dbh->do(scalar read_file($c->config->{root} . '/initial_schema.sql')) or croak 'could not import initial schema';
$c->stash({instance => $data->{id}});
$self->create_type($c, {id => 'site', name => 'Site', page_element => 0});
$self->create_attribute($c, {type => 'site', id => 'title', name => 'Title', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''});
$self->create_attribute($c, {type => 'site', id => 'publish_uri', name => 'Publishing target URI', sort_id => 2, data_type => 'String', repetitive => 0, mandatory => 0, default_value => ''});
$self->create_attribute($c, {type => 'site', id => 'children', name => 'Children', sort_id => 1, data_type => 'Object', repetitive => 1, mandatory => 0, default_value => ''});
$self->initialize($c);
CiderCMS::Object->new({c => $c, type => 'site', dcid => '', data => {title => $data->{title}}})->insert;
return;
}
=head2 instance_exists($instance)
Returns true if an instance with the given name exists in the database.
=cut
sub instance_exists {
my ($self, $instance) = @_;
return $self->dbh->selectrow_array("
select count(*)
from pg_namespace
where
nspowner != 10
and nspname != 'public'
and nspname = ?
",
undef,
$instance
);
}
=head2 initialize($c)
Fetches type and attribute information from the DB and puts it on the stash:
types => {
type1 => {
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
}
Should be called after every change to the schema.
=cut
sub initialize {
my ($self, $c) = @_;
my $dbh = $self->dbh;
my $instance = $c->stash->{instance};
confess 'You did not set $c->stash->{instance} before calling initialize!' unless $instance;
return unless $self->instance_exists($instance);
$dbh->do(qq(set search_path="$instance",public))
or croak qq(could not set search path "$instance",public);
my $types = $dbh->selectall_arrayref('select * from sys_types', {Slice => {}});
my $attrs = $dbh->selectall_arrayref('select * from sys_attributes order by sort_id', {Slice => {}});
my %types = map { $_->{id} => { %$_, attributes => [], attr => {} } } @$types;
foreach (@$attrs) {
push @{ $types{$_->{type}}{attributes} }, $_;
$types{$_->{type}}{attr}{$_->{id}} = $_;
$_->{class} = "CiderCMS::Attribute::$_->{data_type}";
}
$c->stash({
types => \%types,
});
return 1;
}
=head2 traverse_path($c, $path)
Traverses a path (given as hashref) and returns the objects found
=cut
sub traverse_path {
my ($self, $c, $path) = @_;
my @objects;
my $object;
my $dbh = $self->dbh;
my $level = 0;
foreach (@$path) {
my $may_be_id = /\A\d+\z/xm;
$object = $dbh->selectrow_hashref(
'select id, type from sys_object where parent '
. (@objects ? ' = ?' : ' is null')
. ' and ' . ($may_be_id ? '(id=? or dcid=?)' : 'dcid=?'),
undef,
(@objects ? $objects[-1]->{id} : ()),
$_,
($may_be_id ? $_ : ()),
) or croak qq{node "$_" not found\n};
$object->{level} = $level++;
push @objects, $self->inflate_object($c, $object);
}
return @objects;
}
=head2 get_object($c, $id, $level)
Returns a content object for the given ID.
Sets the object's level to the given $level
=cut
#TODO great point to add some caching
sub get_object {
my ($self, $c, $id, $level) = @_;
$level ||= 0;
my $object = $self->dbh->selectrow_hashref('select id, type from sys_object where id = ?', undef, $id);
$object->{level} = $level;
return $self->inflate_object($c, $object);
}
=head2 inflate_object($c, $object)
Takes a stub object (consisting of id, type and level information) and inflates it to a full blown and initialized CiderCMS::Object.
=cut
sub inflate_object {
my ($self, $c, $object) = @_;
my $level = $object->{level};# or $object->{type} ne 'site' and cluck "$object->{type} has no level!";
$object = $self->dbh->selectrow_hashref(qq(select * from "$object->{type}" where id=?), undef, $object->{id});
return CiderCMS::Object->new({c => $c, id => $object->{id}, type => $object->{type}, dcid => $object->{dcid}, parent => $object->{parent}, parent_attr => $object->{parent_attr}, level => $level, sort_id => $object->{sort_id}, data => $object});
}
=head2 object_children($c, $object, $attr)
Returns the children of an object as list in list context and as array ref in scalar context.
=cut
sub object_children {
my ($self, $c, $object, $attr) = @_;
my @children = map {
$self->inflate_object($c, {%$_, level => $object->{level} + 1});
} @{ $self->dbh->selectall_arrayref('select id, type from sys_object where parent = ?' . ($attr ? ' and parent_attr = ?' : '') . ' order by sort_id', {Slice => {}}, $object->{id}, ($attr ? $attr : ())) };
return wantarray ? @children : \@children;
}
=head2 create_type($c, {id => 'type1', name => 'Type 1', page_element => 0})
Creates a new type by creating a database table for it and an entry in the sys_types table.
=cut
sub create_type {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
my $id = $data->{id};
$data->{page_element} ||= 0;
$self->txn_do(sub {
$dbh->do('insert into sys_types (id, name, page_element) values (?, ?, ?)', undef, $id, $data->{name}, $data->{page_element});
$dbh->do(q/set client_min_messages='warning'/); # avoid the CREATE TABLE / PRIMARY KEY will create implicit index NOTICE
$dbh->do(qq/create table "$id" (id integer not null, parent integer, parent_attr varchar, sort_id integer default 0 not null, type varchar not null references sys_types (id) default '$id', changed timestamp not null default now(), tree_changed timestamp not null default now(), active_start timestamp, active_end timestamp, dcid varchar)/);
$dbh->do(q/set client_min_messages='notice'/); # back to full information
$dbh->do(qq/create trigger "${id}_bi" before insert on "$id" for each row execute procedure sys_objects_bi()/);
$dbh->do(qq/create trigger "${id}_bu" before update on "$id" for each row execute procedure sys_objects_bu()/);
$dbh->do(qq/create trigger "${id}_ad" after delete on "$id" for each row execute procedure sys_objects_ad()/);
});
my $path = $c->fs_path_for_instance . '/../templates/types';
unless (-e "$path/$data->{id}.zpt" or -e $c->config->{root} . "/templates/types/$data->{id}.zpt") { #TODO: put this stuff in it's own class. CiderCMS::Type?
make_path($path);
open my $template, '>', "$path/$data->{id}.zpt" or croak "Could not open $path/$data->{id}.zpt: $OS_ERROR";
say { $template } '<div xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS" tal:attributes="id string:object_${self/id}" />';
close $template;
}
$self->initialize($c);
return;
}
=head2 update_type($c, $id, {id => 'type1', name => 'Type 1', page_element => 0})
Updates an existing type.
=cut
sub update_type {
my ($self, $c, $id, $data) = @_;
my $dbh = $self->dbh;
$data->{page_element} ||= 0;
if ($data->{id} ne $id) {
$self->txn_do(sub {
$dbh->do('set constraints "sys_attributes_type_fkey" deferred');
$dbh->do('update sys_types set id = ?, name = ?, page_element = ? where id = ?', undef, @$data{qw(id name page_element)}, $id);
$dbh->do(q/update sys_attributes set type = ? where type = ?/, undef, $data->{id}, $id);
$dbh->do(qq/alter table "$id" rename to "$data->{id}"/);
});
}
else {
$dbh->do('update sys_types set id = ?, name = ?, page_element = ? where id = ?', undef, @$data{qw(id name page_element)}, $id);
}
return;
}
=head2 create_attribute($c, {type => 'type1', id => 'attr1', name => 'Attribute 1', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''})
Adds a new attribute to a type by creating the column in the type's table and an entry in the sys_attributes table.
=cut
sub create_attribute {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
$_ = $_ ? 1 : 0 foreach @$data{qw(mandatory repetitive)};
$self->txn_do(sub {
$dbh->do('insert into sys_attributes (type, id, name, data_type, repetitive, mandatory, default_value) values (?, ?, ?, ?, ?, ?, ?)', undef, @$data{qw(type id name data_type repetitive mandatory default_value)});
if (my $data_type = "CiderCMS::Attribute::$data->{data_type}"->db_type) {
my $query = qq/alter table "$data->{type}" add column "$data->{id}" $data_type/;
$query .= ' not null' if $data->{mandatory};
$query .= ' default ' . $dbh->quote($data->{default}) if defined $data->{default} and $data->{default} ne '';
$dbh->do($query);
}
});
$self->initialize($c);
return;
}
=head2 update_attribute($c, {type => 'type1', id => 'attr1', name => 'Attribute 1', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''})
Updates an existing attribute.
=cut
sub update_attribute {
my ($self, $c, $type, $id, $data) = @_;
my $dbh = $self->dbh;
$_ = $_ ? 1 : 0 foreach @$data{qw(mandatory repetitive)};
$self->txn_do(sub {
$dbh->do('update sys_attributes set id = ?, sort_id = ?, name = ?, data_type = ?, repetitive = ?, mandatory = ?, default_value = ? where type = ? and id = ?', undef, @$data{qw(id sort_id name data_type repetitive mandatory default_value)}, $type, $id);
});
return;
}
=head2 create_insert_aisle({c => $c, parent => $parent, attr => $attr, count => $count, after => $after})
Creates an aisle in the sort order of an object's children to insert new objects in between.
=cut
sub create_insert_aisle {
my ($self, $params) = @_;
my $dbh = $self->dbh;
if ($params->{after}) {
$params->{after} = $self->get_object($params->{c}, $params->{after}) unless ref $params->{after};
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('update sys_object set sort_id = -sort_id where parent = ? and parent_attr = ? and sort_id > ?', undef, $params->{parent}, $params->{attr}, $params->{after}->{sort_id});
$dbh->do("update sys_object set sort_id = -sort_id + $params->{count} where parent = ? and parent_attr = ? and sort_id < 0", undef, $params->{parent}, $params->{attr});
return $params->{after}->{sort_id} + 1;
}
else {
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('update sys_object set sort_id = -sort_id where parent = ? and parent_attr = ?', undef, $params->{parent}, $params->{attr});
$dbh->do("update sys_object set sort_id = -sort_id + $params->{count} where parent = ? and parent_attr = ?", undef, $params->{parent}, $params->{attr});
return 1;
}
}
=head2 close_aisle($c, $parent, $attr, $sort_id)
Closes an aisle in the sort order of an object's children after removing a child.
=cut
sub close_aisle {
my ($self, $c, $parent, $attr, $sort_id) = @_;
my $dbh = $self->dbh;
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('
update sys_object
set sort_id = -sort_id
where parent = ? and parent_attr = ? and sort_id > ?
',
undef,
$parent->{id},
$attr,
$sort_id,
);
$dbh->do('
update sys_object
set sort_id = -sort_id - 1
where parent = ? and parent_attr = ? and sort_id < ?
',
undef,
$parent->{id},
$attr,
-$sort_id,
);
return;
}
=head2 insert_object($c, $object)
Inserts a CiderCMS::Object into the database.
=cut
my @sys_object_columns = qw(id parent parent_attr sort_id type active_start active_end dcid);
sub insert_object {
my ($self, $c, $object, $params) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
local $dbh->{RaiseError} = 1;
return $self->txn_do(sub {
$object->{sort_id} = $self->create_insert_aisle({c => $c, parent => $object->{parent}, attr => $object->{parent_attr}, count => 1, after => $params->{after}});
my ($columns, $values) = $object->get_dirty_columns(); # DBIx::Class::Row yeah
my $insert_statement = qq{insert into "$type" (} . join (q{, }, map { qq{"$_"} } @sys_object_columns, @$columns) . ') values (' . join (q{, }, map { '?' } @sys_object_columns, @$columns) . ')';
if (my $retval = $dbh->do($insert_statement, undef, (map { $object->{$_} } @sys_object_columns), @$values)) {
$object->{id} = $dbh->last_insert_id(undef, undef, 'sys_object', undef, {sequence => 'sys_object_id_seq'});
return $retval;
}
});
}
=head2 update_object($c, $object)
Updates a CiderCMS::Object in the database.
=cut
sub update_object {
my ($self, $c, $object) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
my ($columns, $values) = $object->get_dirty_columns(); # DBIx::Class::Row yeah
my $update_statement = qq{update "$type" set } . join (q{, }, map { qq{"$_" = ?} } @sys_object_columns, @$columns) . ' where id = ?';
if (my $retval = $dbh->do($update_statement, undef, (map { $object->{$_} } @sys_object_columns), @$values, $object->{id})) {
return $retval;
}
else {
croak $dbh->errstr;
}
}
=head2 delete_object($c, $object)
Deletes a CiderCMS::Object from the database.
=cut
sub delete_object {
my ($self, $c, $object) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
if (my $retval = $dbh->do(qq{delete from "$type" where id = ?}, undef, $object->{id})) {
$self->close_aisle($c, $object->parent, $object->{parent_attr}, $object->{sort_id});
return $retval;
}
else {
croak $dbh->errstr;
}
}
=head2 move_object($c, $object, $params)
Moves a CiderCMS::Object to a new parent and or sort position
=cut
sub move_object {
my ($self, $c, $object, $params) = @_;
my ($old_parent, $old_parent_attr, $old_sort_id);
if ($params->{parent} and $params->{parent} != $object->{parent} or $params->{parent_attr} and $params->{parent_attr} ne $object->{parent_attr}) {
$old_parent = $object->parent;
$old_parent_attr = $object->{parent_attr};
$old_sort_id = $object->{sort_id};
$object->{parent} = $params->{parent}{id};
$object->{parent_attr} = $params->{parent_attr};
}
$object->{sort_id} = $self->create_insert_aisle({c => $c, parent => $object->{parent}, attr => $object->{parent_attr}, count => 1, after => $params->{after}});
my $result = $self->update_object($c, $object);
if ($old_parent) {
$self->close_aisle($c, $old_parent, $old_parent_attr, $old_sort_id);
}
return $result;
}
=head2 instances()
Returns a list of all instances.
=cut
sub instances {
my ($self) = @_;
return $self->dbh->selectcol_arrayref(q[
select nspname
from pg_namespace
where nspowner != 10 and nspname != 'public'
order by nspname
]);
}
=head2 txn_do($code)
Run $sub in a transaction. Rollback transaction if $sub dies.
=cut
sub txn_do {
my ($self, $code) = @_;
my $dbh = $self->dbh;
my $in_txn = not $dbh->{AutoCommit};
$dbh->begin_work unless $in_txn;
my ($result, @results);
if (wantarray) {
- @results = $code->();
+ @results = eval { $code->() };
}
else {
- $result = $code->();
+ $result = eval { $code->() };
}
$dbh->commit unless $in_txn or $dbh->{AutoCommit};
return wantarray ? @results : $result;
}
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
DBI Model Class.
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
|
niner/CiderCMS
|
b9db19a0461b8e95c77657207193ba6227c35b16
|
Allow cut&pasting multiple objects at once
|
diff --git a/lib/CiderCMS/Controller/Content/Management.pm b/lib/CiderCMS/Controller/Content/Management.pm
index de7f4a9..d2881e2 100644
--- a/lib/CiderCMS/Controller/Content/Management.pm
+++ b/lib/CiderCMS/Controller/Content/Management.pm
@@ -1,171 +1,187 @@
package CiderCMS::Controller::Content::Management;
use strict;
use warnings;
use parent 'Catalyst::Controller';
=head1 NAME
CiderCMS::Controller::Content::Management - Catalyst Controller
=head1 DESCRIPTION
Controller for managing content.
=head1 METHODS
=head2 auto
Sets up context information according to the current path
=cut
sub auto : Private {
my ( $self, $c ) = @_;
my $model = $c->model('DB');
$c->stash({
uri_manage_types => $c->uri_for_instance('system/types'),
uri_manage_content => $model->get_object($c, 1)->uri_management,
uri_view => $c->stash->{context}->uri_index,
management => 1,
});
my $actions = CiderCMS->management_actions;
$c->stash->{actions} = [ map { $actions->{$_}->($_, $c) } keys %$actions ];
return 1;
}
=head2 manage
Shows a management interface for the current node.
=cut
sub manage : CiderCMS('manage') {
my ( $self, $c ) = @_;
my %params = %{ $c->req->params };
my $save = delete $params{save};
my $context = $c->stash->{context};
my $errors;
if ($save) {
unless ($errors = $context->validate(\%params)) {
$context->update({data => \%params});
# return to the parent for page_elements and stay at the element for pages.
return $c->res->redirect(
($context->type->{page_element} ? $context->parent : $context)->uri_management()
);
}
}
$c->stash({ # values used by edit_form()
uri_add => $context->uri . '/manage_add',
uri_delete => $context->uri . '/manage_delete',
});
$c->stash({
template => 'manage.zpt',
content => $c->stash->{context}->edit_form($errors),
});
return;
}
=head2 manage_add
Adds a new object as child of the current node.
=cut
sub manage_add : CiderCMS('manage_add') {
my ( $self, $c ) = @_;
my %params = %{ $c->req->params };
my $type = delete $params{type};
my $parent_attr = delete $params{parent_attr};
my $save = delete $params{save};
my $after = delete $params{after};
my $context = $c->stash->{context};
my $object = $context->new_child(
attribute => $parent_attr,
type => $type,
);
my $errors;
if ($save) {
unless ($errors = $object->validate(\%params)) {
$object->insert({after => $after, data => \%params});
return $c->res->redirect(
($object->type->{page_element} ? $context : $object)->uri_management()
);
}
}
else {
$object->init_defaults;
}
$c->stash({
type => $type,
after => $after,
parent_attr => $parent_attr,
uri_action => $context->uri . '/manage_add',
template => 'manage.zpt',
content => $object->edit_form($errors),
errors => $errors // {},
});
return;
}
=head2 manage_delete
Deletes a child of the current node.
=cut
sub manage_delete : CiderCMS('manage_delete') {
my ( $self, $c ) = @_;
my $id = $c->req->param('id');
my $object = $c->model('DB')->get_object($c, $id);
$object->delete_from_db;
return $c->res->redirect($c->stash->{context}->uri_management());
}
=head2 manage_paste
Cut and past an object to a new location.
=cut
sub manage_paste : CiderCMS('manage_paste') {
my ( $self, $c ) = @_;
- my $object = $c->model('DB')->get_object($c, $c->req->param('id'));
-
- $object->move_to(parent => $c->stash->{context}, parent_attr => scalar $c->req->param('attribute'), after => scalar $c->req->param('after'));
+ my @ids = $c->req->param('id');
+ my $db = $c->model('DB');
+
+ $db->txn_do(sub {
+ my $after = $c->req->params->{after};
+ my $attribute = $c->req->params->{attribute};
+
+ foreach my $id (@ids) {
+ my $object = $db->get_object($c, $id);
+ next unless $object;
+ $object->move_to(
+ parent => $c->stash->{context},
+ parent_attr => $attribute,
+ after => $after,
+ );
+ $object->refresh;
+ $after = $object;
+ }
+ });
return $c->res->redirect($c->stash->{context}->uri_management());
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Object.pm b/lib/CiderCMS/Object.pm
index 5799797..49b0fb7 100644
--- a/lib/CiderCMS/Object.pm
+++ b/lib/CiderCMS/Object.pm
@@ -1,587 +1,599 @@
package CiderCMS::Object;
use strict;
use warnings;
use Scalar::Util qw(weaken);
use List::MoreUtils qw(any none);
use File::Path qw(mkpath);
use File::Copy qw(move);
use Carp qw(croak);
use CiderCMS::Attribute;
=head1 NAME
CiderCMS::Object - Content objects
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
This class is the base for all content objects and provides the public API that can be used in templates.
=head1 METHODS
=head2 new({c => $c, id => 2, type => 'type1', parent => 1, parent_attr => 'children', sort_id => 0, data => {}})
=cut
sub new {
my ($class, $params) = @_;
$class = ref $class if ref $class;
my $c = $params->{c};
my $stash = $c->stash;
my $type = $params->{type};
my $data = $params->{data};
my $self = bless {
c => $params->{c},
id => $params->{id},
parent => $params->{parent},
parent_attr => $params->{parent_attr},
level => $params->{level},
type => $type,
sort_id => $params->{sort_id} || 0,
dcid => $params->{dcid},
attr => $stash->{types}{$type}{attr},
attributes => $stash->{types}{$type}{attributes},
}, $class;
weaken($self->{c});
foreach my $attr (@{ $self->{attributes} }) {
my $id = $attr->{id};
$self->{data}{$id} = $attr->{class}->new({c => $c, object => $self, data => $data->{$id}, %$attr});
}
return $self;
}
=head2 object_by_id($id)
Returns an object for the given ID
=cut
sub object_by_id {
my ($self, $id) = @_;
return $self->{c}->model('DB')->get_object($self->{c}, $id);
}
+=head2 id
+
+Returns this object's id.
+
+=cut
+
+sub id {
+ my ($self) = @_;
+
+ return $self->{id};
+}
+
=head2 type
Returns the type info for this object.
For example:
{
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
=cut
sub type {
my ($self) = @_;
return $self->{c}->stash->{types}{$self->{type}};
}
=head2 property($property)
Returns the data of the named attribute
=cut
sub property {
my ($self, $property, $default) = @_;
unless (exists $self->{data}{$property}) {
return $default if @_ == 3;
croak "unknown property $property";
}
return $self->{data}{$property}->data;
}
=head2 set_property($property, $data)
Sets the named attribute to the given value
=cut
sub set_property {
my ($self, $property, $data) = @_;
return $self->{data}{$property}->set_data($data);
}
=head2 attribute($attribute)
Returns the CiderCMS::Attribute object for the named attribute
=cut
sub attribute {
my ($self, $attribute) = @_;
return unless exists $self->{data}{$attribute};
return $self->{data}{$attribute};
}
=head2 update_data($data)
Updates this object's data from a hashref.
=cut
sub update_data {
my ($self, $data) = @_;
foreach (values %{ $self->{data} }) {
$_->set_data_from_form($data);
}
return;
}
=head2 init_defaults()
Initialize this object's data to the attributes' default values.
=cut
sub init_defaults {
my ($self) = @_;
$_->init_default foreach values %{ $self->{data} };
return;
}
=head2 parent
Returns the parent of this object, if any.
=cut
sub parent {
my ($self) = @_;
return unless $self->{parent};
return $self->{c}->model('DB')->get_object($self->{c}, $self->{parent}, $self->{level} - 1);
}
=head2 parents
Returns the parent chain of this object including the object itself.
=cut
sub parents {
my ($self) = @_;
my $parent = $self;
my @parents = $parent;
unshift @parents, $parent while $parent = $parent->parent;
return \@parents;
}
=head2 parent_by_level($level)
Returns the parent at a certain level.
The site object is at level 0.
=cut
sub parent_by_level {
my ($self, $level) = @_;
return if $self->{level} < $level; # already on a lower level
my $parent = $self;
while ($parent) {
return $parent if $parent->{level} == $level;
$parent = $parent->parent;
}
return;
}
=head2 children()
Returns the children of this object regardless to which attribute they belong.
Usually one should use $object->property('my_attribute') to only get the children of a certain attribute.
Returns a list in list context and an array ref in scalar context.
=cut
sub children {
my ($self) = @_;
return $self->{c}->model('DB')->object_children($self->{c}, $self);
}
=head2 uri()
Returns an URI without a file name for this object
=cut
sub uri {
my ($self) = @_;
my $parent = $self->parent;
my $dcid = ($self->{dcid} // $self->{id});
return ( ($parent ? $parent->uri : $self->{c}->uri_for_instance()) . ($dcid ? "/$dcid" : '') );
}
=head2 uri_index()
Returns an URI to the first object in this subtree that contains page elements.
If none does, return the URI to the first child.
=cut
sub uri_index {
my ($self) = @_;
my @children = $self->children;
if (not @children or any { $_->type->{page_element} } @children) { # we contain no children at all or page elements
return $self->uri . '/index.html';
}
else {
return $children[0]->uri_index;
}
}
=head2 uri_management()
Returns an URI to the management interface for this object
=cut
sub uri_management {
my ($self) = @_;
return $self->uri . '/manage';
}
=head2 uri_static()
Returns an URI for static file for this object
=cut
sub uri_static {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->uri_static : $self->{c}->uri_static_for_instance()) . "/$self->{id}" );
}
=head2 fs_path()
Returns the file system path to this node
=cut
sub fs_path {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->fs_path : $self->{c}->fs_path_for_instance()) . "/$self->{id}" );
}
=head2 edit_form($errors)
Renders the form for editing this object.
The optional $errors may be a hash reference with error messages for attributes.
=cut
sub edit_form {
my ($self, $errors) = @_;
$errors //= {};
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => 'edit.zpt',
self => $self,
attributes => [
map {
$self->{data}{$_->{id}}->input_field($errors->{$_->{id}})
} @{ $self->{attributes} },
],
});
}
=head2 render()
Returns an HTML representation of this object.
=cut
sub render {
my ($self) = @_;
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => "types/$self->{type}.zpt",
self => $self,
});
}
=head2 validate($data)
Validate the given data.
Returns a hash containing messages for violated constraints:
{
attr1 => ['missing'],
attr2 => ['invalid', 'wrong'],
}
=cut
sub validate {
my ($self, $data) = @_;
my %results;
foreach (values %{ $self->{data} }) {
my @result = $_->validate($data);
$results{ $_->{id} } = \@result if @result;
}
return \%results if keys %results;
return;
}
=head2 prepare_attributes()
Prepares attributes for insert and update operations.
=cut
sub prepare_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->prepare_update();
}
return;
}
=head2 update_attributes()
Runs update operation on attributes after inserts and updates.
=cut
sub update_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->post_update();
}
return;
}
=head2 insert({after => $after})
Inserts the object into the database.
=cut
sub insert {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data(delete $params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->insert_object($self->{c}, $self, $params);
$self->update_attributes;
return $result;
}
=head2 update()
Updates the object in the database.
=cut
sub update {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data($params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->update_object($self->{c}, $self);
$self->update_attributes;
return $result;
}
=head2 delete_from_db()
Deletes the object and it's children.
=cut
sub delete_from_db {
my ($self) = @_;
foreach ($self->children) {
$_->delete_from_db;
}
return $self->{c}->model('DB')->delete_object($self->{c}, $self);
}
=head2 get_dirty_columns()
Returns two array refs with column names and corresponding values.
=cut
sub get_dirty_columns {
my ($self) = @_;
my (@columns, @values);
foreach (@{ $self->{attributes} }) {
my $id = $_->{id};
my $attr = $self->{data}{$id};
if ($attr->db_type) {
push @columns, $id;
push @values, $attr->{data}; #TODO introduce an $attr->raw_data
}
}
return \@columns, \@values;
}
=head2 move_to(parent => $parent, parent_attr => $parent_attr, after => $after)
Moves this object (and it's subtree) to a new parent and or sort position
=cut
sub move_to {
my ($self, %params) = @_;
my $old_fs_path = $self->fs_path;
my $result = $self->{c}->model('DB')->move_object($self->{c}, $self, \%params);
if (-e $old_fs_path) {
my $new_fs_path = $self->fs_path;
mkpath $self->parent->fs_path if $self->{parent};
move $old_fs_path, $new_fs_path;
}
return $result;
}
=head2 refersh()
Reloads this object from the database.
=cut
sub refresh {
my ($self) = @_;
my $fresh = $self->{c}->model('DB')->get_object($self->{c}, $self->{id});
%$self = %$fresh;
return $self;
}
=head2 new_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in memory for the given attribute.
=cut
sub new_child {
my ($self, %params) = @_;
$params{c} = $self->{c};
$params{parent} = $self->{id};
$params{level} = $self->{level};
$params{parent_attr} = delete $params{attribute};
croak "Invalid attribute: $params{parent_attr}"
unless exists $self->{data}{ $params{parent_attr} };
return CiderCMS::Object->new(\%params);
}
=head2 create_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in the database for the given attribute.
=cut
sub create_child {
my ($self, %params) = @_;
# Don't give data to new_child. Instead give it to insert so it gets treated like
# data subitted through the management UI.
my $data = delete $params{data};
my $child = $self->new_child(%params);
$child->insert({data => $data});
return $child;
}
=head2 user_has_access
Returns whether the currently logged in user has access to this folder and all
parent folders.
=cut
sub user_has_access {
my ($self) = @_;
my $user = $self->{c}->user;
return 1 if $user;
diff --git a/root/static/css/management.css b/root/static/css/management.css
index 4c28ec8..06f8524 100644
--- a/root/static/css/management.css
+++ b/root/static/css/management.css
@@ -1,164 +1,164 @@
body {
margin: 0;
}
#navigation {
list-style: none;
margin: 0;
padding: 0.1em 0;
overflow: auto;
background-color: #e8e8e8;
border-width: 0 2px 2px 0;
border-style: solid;
border-color: #70a0ff;
border-bottom-right-radius: 8px;
-khtml-border-bottom-right-radius: 8px;
-moz-border-radius-bottomright: 8px;
-webkit-border-bottom-right-radius: 8px;
float: left;
}
#navigation li {
float: left;
padding: 0 0.5em;
margin-right: 0.5em;
border: 1px solid transparent;
}
#navigation li:hover {
border: 1px solid #80c0ff;
border-radius: 5px;
-khtml-border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}
#navigation li a {
color: black;
text-decoration: none;
}
#content {
clear: left;
padding: 1em;
}
fieldset {
margin-top: 1em;
border: 1px solid gray;
border-radius: 8px;
-khtml-border-radius: 8px;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
}
a img {
border: none;
}
div.child {
border: 1px solid #80c0ff;
margin-bottom: 0.5em;
padding: 0.5em;
min-height: 2.5em;
}
div.child div.actions {
float: left;
- width: 140px; /* icons have static width */
+ width: 170px; /* icons have static width */
}
div.child div.actions > .icon {
border: 1px solid transparent;
border-radius: 5px;
-khtml-border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
padding: 0 2px;
}
div.child div.actions > .icon:hover {
border-color: #80c0ff;
}
div.child div.actions > .icon img {
vertical-align: middle;
}
div.child div.child_content {
margin-left: 145px;
}
div.child div.folder a {
font-size: 150%;
}
.add_child {
display: inline;
position: relative;
}
.add_child ul {
display: none;
position: absolute;
z-index: 10;
top: 0.9em;
left: 0;
list-style: none;
margin: 0;
padding: 0.2em 0.3em;
background-color: white;
border: 1px solid #80c0ff;
border-radius: 5px;
-khtml-border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
white-space: nowrap;
}
.add_child:hover ul {
display: block;
}
.add_child ul a {
text-decoration: none;
}
label {
display: block;
clear: left;
overflow: auto;
}
label > span {
float: left;
width: 20%;
}
label input[name=date] {
width: 7em;
}
label span.errors {
color: red;
}
label span.errors:before {
content: "(";
}
label span.errors:after {
content: ")";
}
textarea {
width: 42em;
height: 35em;
}
.repeat_error {
display: none;
float: none;
width: auto;
margin-left: 20%;
}
diff --git a/root/static/js/scripts.js b/root/static/js/scripts.js
index 5b1467a..1f0138c 100644
--- a/root/static/js/scripts.js
+++ b/root/static/js/scripts.js
@@ -1,35 +1,54 @@
+'use strict;'
+
+function find_selected_ids() {
+ var checkboxes = document.querySelectorAll('input.cidercms_multi_selector');
+ var ids = [];
+ [].forEach.call(checkboxes, function (checkbox) {
+ if (checkbox.checked)
+ ids.push(checkbox.getAttribute('data-id'));
+ });
+ return ids;
+}
+
function cut(id) {
+ var selected = find_selected_ids();
+ if (selected.length)
+ id = selected.join(',')
document.cookie = 'id=' + id + '; path=/'
return;
}
function paste(link, after) {
- id = document.cookie.match(/\bid=\d+/);
- var href = link.href + ';' + id;
+ var ids = document.cookie.match(/\bid=(\d+(,\d+)+)/)[1].split(',');
+
+ var href = link.href;
+ ids.forEach(function(id) {
+ href += ';id=' + id;
+ });
if (after)
href += ';after=' + after;
location.href = href;
return false;
}
document.addEventListener("DOMContentLoaded", function() {
var edit_object_form = document.getElementById('edit_object_form');
if (edit_object_form) {
edit_object_form.onsubmit = function() {
var password = edit_object_form.querySelector('label.password input');
var repeat = edit_object_form.querySelector('label.password_repeat input');
if (password && repeat) {
var repeat_error = repeat.parentNode.querySelector('.repeat_error');
if (password.value == repeat.value) {
repeat_error.style.display = '';
return true;
}
else {
repeat_error.style.display = 'block';
alert(false);
return false;
}
}
}
}
}, false);
diff --git a/root/templates/attributes/object.zpt b/root/templates/attributes/object.zpt
index 7cc4d16..602bb86 100644
--- a/root/templates/attributes/object.zpt
+++ b/root/templates/attributes/object.zpt
@@ -1,34 +1,35 @@
<fieldset xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS" tal:condition="true: self/object/id">
<legend tal:content="self/name"/>
<div class="add_child">
<a class="icon paste" tal:attributes="href string:${self/object/uri_management}_paste?attribute=${self/id}; onclick string:return paste(this)"><img tal:attributes="src string:${uri_sys_static}/images/icons/paste.png" title="paste" alt="paste"/></a>
<img tal:attributes="src string:${uri_sys_static}/images/icons/add.png" title="add child" alt="add child"/>
<ul>
<li tal:condition="true: addable_types" tal:repeat="type addable_types">
<a tal:attributes="href string:${uri_add}?type=${type/id}\;parent_attr=${self/id}" tal:content="string: Add ${type/name}"/>
</li>
</ul>
</div>
<div class="children">
<div tal:condition="true: children" tal:repeat="child children" class="child" tal:attributes="class string:child ${child/type/id}; id string:child_${child/id}">
<div class="actions">
<div><a tal:attributes="href child/uri_management" tal:content="child/type/name"/></div>
+ <input type="checkbox" class="cidercms_multi_selector" tal:attributes="data-id child/id"/>
<a class="icon" tal:attributes="href child/uri_management"><img tal:attributes="src string:${uri_sys_static}/images/icons/edit.png" title="edit" alt="edit"/></a>
<span class="icon" tal:attributes="onclick string:cut(${child/id})"><img tal:attributes="src string:${uri_sys_static}/images/icons/cut.png" title="cut" alt="cut"/></span>
<a class="icon paste" tal:attributes="href string:${self/object/uri_management}_paste?attribute=${self/id}; onclick string:return paste(this, ${child/id})"><img tal:attributes="src string:${uri_sys_static}/images/icons/paste.png" title="paste" alt="paste"/></a>
<a class="icon" tal:attributes="href string:${uri_delete}?id=${child/id}"><img tal:attributes="src string:${uri_sys_static}/images/icons/delete.png" title="delete" alt="delete"/></a>
<div class="icon add_child">
<img tal:attributes="src string:${uri_sys_static}/images/icons/add.png" title="add child" alt="add child"/>
<ul>
<li tal:condition="true: addable_types" tal:repeat="type addable_types">
<a tal:attributes="href string:${uri_add}?type=${type/id}\;parent_attr=${self/id}\;after=${child/id}" tal:content="string: Add ${type/name}"/>
</li>
</ul>
</div>
</div>
<div class="child_content" tal:content="structure child/render"/>
</div>
</div>
</fieldset>
diff --git a/t/paste.t b/t/paste.t
new file mode 100644
index 0000000..5b098ec
--- /dev/null
+++ b/t/paste.t
@@ -0,0 +1,46 @@
+use strict;
+use warnings;
+use utf8;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+
+CiderCMS::Test->populate_types({
+ CiderCMS::Test->std_folder_type,
+ CiderCMS::Test->std_textfield_type,
+});
+
+my $root = $model->get_object($c, 1);
+ my $source = $root->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Source' },
+ );
+ my @texts = reverse map {
+ $source->create_child(
+ attribute => 'children',
+ type => 'textfield',
+ data => {
+ text => "$_",
+ },
+ );
+ } reverse 1 .. 10;
+ my $destination = $root->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Destination' },
+ );
+
+my $paste = URI->new($destination->uri . '/manage_paste');
+$paste->query_form(
+ attribute => 'children',
+ after => '',
+ id => [ map { $_->id } @texts[1, 3, 5] ],
+);
+$mech->get($paste);
+
+my @children = $destination->attribute('children')->data;
+is(scalar @children, 3);
+is(join(', ', map { $_->property('text') } @children), '2, 4, 6');
+
+done_testing;
|
niner/CiderCMS
|
d07d9a2dd26438356d569bcb232f56e3f9bea067
|
Reduce duplicated test code for creating common types
|
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index 4921110..995108e 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,205 +1,245 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
=head2 context
Returns a $c object for tests.
=cut
sub context {
my ($self) = @_;
require Catalyst::Test;
Catalyst::Test->import('CiderCMS');
my ($res, $c) = ctx_request('/system/create');
delete $c->stash->{$_} foreach keys %{ $c->stash };
return $c;
}
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
$ENV{ CIDERCMS_CONFIG_LOCAL_SUFFIX } = 'test';
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
my $c = $self->context;
my $model = $c->model('DB');
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
+=head3 std_folder_type
+
+=cut
+
+sub std_folder_type {
+ return folder => {
+ name => 'Folder',
+ attributes => [
+ {
+ id => 'title',
+ data_type => 'Title',
+ mandatory => 1,
+ },
+ {
+ id => 'children',
+ data_type => 'Object',
+ mandatory => 0,
+ repetitive => 1,
+ },
+ ],
+ };
+}
+
+=head3 std_textfield_type
+
+=cut
+
+sub std_textfield_type {
+ return textfield => {
+ name => 'Textfield',
+ attributes => [
+ {
+ id => 'text',
+ data_type => 'Text',
+ mandatory => 1,
+ },
+ ],
+ };
+}
+
sub write_template {
my ($self, $file, $contents) = @_;
write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
}
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
undef $mech;
}
1;
diff --git a/t/custom_reservation.t b/t/custom_reservation.t
index 92f1784..2eee3a0 100644
--- a/t/custom_reservation.t
+++ b/t/custom_reservation.t
@@ -1,303 +1,290 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
CiderCMS::Test->populate_types({
- folder => {
- name => 'Folder',
- attributes => [
- {
- id => 'title',
- mandatory => 1,
- },
- {
- id => 'children',
- data_type => 'Object',
- repetitive => 1,
- },
- ],
- },
+ CiderCMS::Test->std_folder_type,
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'name',
data_type => 'String',
},
],
},
reservation => {
name => 'Reservation',
page_element => 1,
attributes => [
{
id => 'start',
data_type => 'DateTime',
mandatory => 1,
},
{
id => 'end',
data_type => 'Time',
mandatory => 1,
},
{
id => 'user',
data_type => 'String',
},
{
id => 'info',
data_type => 'String',
},
{
id => 'cancelled_by',
data_type => 'String',
},
],
},
airplane => {
name => 'Airplane',
page_element => 1,
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'reservations',
data_type => 'Object',
repetitive => 1,
},
{
id => 'reservation_time_limit',
data_type => 'Integer',
},
],
template => 'airplane.zpt'
},
});
my $root = $model->get_object($c, 1);
my $users = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Users' },
);
$users->create_child(
attribute => 'children',
type => 'user',
data => {
username => 'test',
name => 'test',
password => 'test',
},
);
my $airplanes = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Airplanes' },
);
my $dimona = $airplanes->create_child(
attribute => 'children',
type => 'airplane',
data => {
title => 'Dimona',
},
);
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->content_contains('Keine Reservierungen eingetragen.');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
$mech->content_lacks('Keine Reservierungen eingetragen.');
ok($mech->find_xpath(qq{//td[span="Heute"]}), "Today's reservation listed");
ok($mech->find_xpath(qq{//td[text()="test"]}), 'reserving user listed');
ok($mech->find_xpath(qq{//td[text()="Testflug"]}), 'Info listed');
$date->add(days => 1);
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
ok($mech->find_xpath(q{//td[span="Heute"]}), "Today's reservation still listed");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
$mech->get_ok(
$mech->find_xpath(q{//tr[td="Heute"]/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
is('' . $mech->find_xpath(q{//td[text()="Heute"]}), '', "Today's reservation gone");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/6/manage");
is($mech->value('cancelled_by'), 'test');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "conflicting existent reservation"]'),
'error message for conflict with existent reservation found'
);
$mech->get_ok("http://localhost/system/logout");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->get_ok(
$mech->find_xpath(q{//tr/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
not($mech->find_xpath('//span[text() = "conflicting existent reservation"]')),
'error message for conflict with existent reservation not found anymore'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
# test error handling
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => 'invalid',
start_time => 'nonsense',
end => 'forget',
info => '',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $year = DateTime->now->add(years => 1)->year;
$mech->submit_form_ok({
with_fields => {
start_date => "6.12.$year",
start_time => '10:00',
end => '13:00',
info => '',
},
button => 'save',
});
ok(not($mech->find_xpath('//span[text() = "invalid"]')), 'valid date -> no error message');
$model->dbh->rollback;
});
$model->txn_do(sub {
# Update to test advance time limit
$dimona->set_property(reservation_time_limit => 24);
$dimona->update;
my $now = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->clone->add(hours => 1)->hms,
end => $now->clone->add(hours => 2)->hms,
info => 'too close',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "too close"]'), 'error message for too close date found');
$now = DateTime->now->add(days => 2)->add(hours => 4);
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->hms,
end => $now->clone->add(hours => 1)->hms,
info => 'too close',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too close"]'),
'',
'error message for too close date gone'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
ok($mech->find_xpath(qq{//p[text()="Frei"]}), "No reservation active for now");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->subtract(hours => 1)->hms(':'),
end => $date->clone->add(hours => 2)->hour . ':00',
info => 'Testflug',
},
button => 'save',
});
is('' . $mech->find_xpath(qq{//p[text()="Frei"]}), '', "Reservation active for now");
$model->dbh->rollback;
});
done_testing;
diff --git a/t/move.t b/t/move.t
index d9e9582..41a9e16 100644
--- a/t/move.t
+++ b/t/move.t
@@ -1,106 +1,83 @@
use strict;
use warnings;
use utf8;
-use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use CiderCMS::Test (test_instance => 1);
use Test::More;
CiderCMS::Test->populate_types({
- folder => {
- name => 'Folder',
- attributes => [
- {
- id => 'title',
- data_type => 'Title',
- mandatory => 1,
- },
- {
- id => 'children',
- data_type => 'Object',
- mandatory => 0,
- },
- ],
- },
- textfield => {
- name => 'Textfield',
- attributes => [
- {
- id => 'text',
- data_type => 'Text',
- mandatory => 1,
- },
- ],
- },
+ CiderCMS::Test->std_folder_type,
+ CiderCMS::Test->std_textfield_type,
});
my $root = $model->get_object($c, 1);
my $source = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Source' },
);
my @texts = reverse map {
$source->create_child(
attribute => 'children',
type => 'textfield',
data => {
text => "$_",
},
);
} reverse 1 .. 10;
my $destination = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Destination' },
);
source_in_order();
# move #1 text from source to destination
my $moving = shift @texts;
$moving->move_to(parent => $destination, parent_attr => 'children');
my @moved = $moving;
$_->refresh foreach @texts;
is_deeply [ map { $_->{sort_id} } @texts ], [ 1 .. @texts ];
is($moving->refresh->{sort_id}, 1);
source_in_order();
# move #3 text from source to destination
($moving) = splice @texts, 1, 1;
$moving->move_to(parent => $destination, parent_attr => 'children');
push @moved, $moving;
source_in_order();
$_->refresh foreach @moved;
is_deeply [ map { $_->{sort_id} } @moved ], [2, 1];
# move #5 text from source to destination after first
($moving) = splice @texts, 2, 1;
$moving->move_to(parent => $destination, parent_attr => 'children', after => $moved[1]);
push @moved, $moving;
source_in_order();
$_->refresh foreach @moved;
is_deeply [ map { $_->{sort_id} } @moved ], [3, 1, 2];
# move last text from source to destination after last
($moving) = pop @texts;
$moving->move_to(parent => $destination, parent_attr => 'children', after => $moved[0]);
push @moved, $moving;
source_in_order();
$_->refresh foreach @moved;
is_deeply [ map { $_->{sort_id} } @moved ], [3, 1, 2, 4];
is_deeply [ map { $_->property('text') } @moved ], [1, 3, 5, 10], 'sanity check moved texts';
done_testing;
sub source_in_order {
$_->refresh foreach @texts;
is_deeply
[ map { $_->{sort_id} } @texts ],
[ 1 .. @texts ],
@texts . ' source texts have correct sort_id';
}
|
niner/CiderCMS
|
152a011a73118558262699fdd7d29ab3ff5b0cff
|
Port gallery_import.t to parallel test infrastructure
|
diff --git a/t/14_gallery_import.t b/t/14_gallery_import.t
deleted file mode 100644
index b8ff317..0000000
--- a/t/14_gallery_import.t
+++ /dev/null
@@ -1,79 +0,0 @@
-use strict;
-use warnings;
-use utf8;
-
-use Test::More;
-use FindBin qw($Bin);
-
-eval "use Test::WWW::Mechanize::Catalyst 'CiderCMS'";
-plan skip_all => "Test::WWW::Mechanize::Catalyst required: $@" if $@;
-
-ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
-
-$mech->get_ok( 'http://localhost/test.example/system/types' );
-
-# add a gallery type
-$mech->submit_form_ok({
- with_fields => {
- id => 'gallery',
- name => 'Gallery',
- page_element => 0,
- },
- button => 'save',
-}, 'Create gallery type');
-$mech->submit_form_ok({
- with_fields => {
- id => 'title',
- name => 'Title',
- data_type => 'Title',
- mandatory => 1,
- },
-}, 'Add images attribute');
-$mech->submit_form_ok({
- with_fields => {
- id => 'images',
- name => 'Images',
- data_type => 'Object',
- mandatory => 0,
- repetitive => 1,
- },
-}, 'Add images attribute');
-
-$mech->get_ok( 'http://localhost/test.example/system/types' );
-
-# add a gallery type
-$mech->submit_form_ok({
- with_fields => {
- id => 'gallery_image',
- name => 'Gallery image',
- page_element => 1,
- },
- button => 'save',
-}, 'Create gallery image type');
-$mech->submit_form_ok({
- with_fields => {
- id => 'image',
- name => 'Image',
- data_type => 'Image',
- mandatory => 1,
- },
-}, 'Add image attribute');
-
-system ('/bin/cp', '-r', "$Bin/test.example/import", "$Bin/../root/instances/test.example/");
-
-$mech->get_ok( 'http://localhost/test.example/manage' );
-$mech->content_lacks('Import images');
-
-$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=gallery} }, 'Add a gallery');
-$mech->submit_form_ok({
- with_fields => {
- title => 'Gallery',
- },
- button => 'save',
-});
-
-$mech->follow_link_ok({ text => 'Import images' }, 'Import is now available');
-
-is(scalar @{ $mech->find_all_links(text => 'Gallery image') }, 2, 'Images imported');
-
-done_testing;
diff --git a/t/gallery_import.t b/t/gallery_import.t
new file mode 100644
index 0000000..ca59095
--- /dev/null
+++ b/t/gallery_import.t
@@ -0,0 +1,56 @@
+use strict;
+use warnings;
+use utf8;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+use FindBin qw($Bin);
+
+CiderCMS::Test->populate_types({
+ gallery => {
+ name => 'Gallery',
+ attributes => [
+ {
+ id => 'title',
+ data_type => 'Title',
+ mandatory => 1,
+ },
+ {
+ id => 'images',
+ data_type => 'Object',
+ mandatory => 0,
+ repetitive => 1,
+ },
+ ],
+ },
+ gallery_image => {
+ name => 'Gallery image',
+ page_element => 1,
+ attributes => [
+ {
+ id => 'image',
+ data_type => 'Image',
+ mandatory => 1,
+ },
+ ],
+ },
+});
+
+system ('/bin/cp', '-r', "$Bin/test.example/import", "$Bin/../root/instances/$instance/");
+
+$mech->get_ok( "http://localhost/$instance/manage" );
+$mech->content_lacks('Import images');
+
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=gallery} }, 'Add a gallery');
+$mech->submit_form_ok({
+ with_fields => {
+ title => 'Gallery',
+ },
+ button => 'save',
+});
+
+$mech->follow_link_ok({ text => 'Import images' }, 'Import is now available');
+
+is(scalar @{ $mech->find_all_links(text => 'Gallery image') }, 2, 'Images imported');
+
+done_testing;
diff --git a/t/paste.t b/t/move.t
similarity index 100%
rename from t/paste.t
rename to t/move.t
|
niner/CiderCMS
|
9fb1952aa14e8b0f274e46b77c585d59b9c77d67
|
Decouple user list from registration to allow making user list private
|
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index a42459c..44612ce 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,105 +1,111 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
use utf8;
use parent 'Catalyst::Controller';
use Email::Sender::Simple;
use Email::Stuffer;
use Encode qw(encode);
use Hash::Merge qw(merge);
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
unless ($errors) {
$errors = merge(
$self->check_email_whitelist($c, $params),
$self->check_duplicates($c, $params),
);
}
if ($errors) {
$_ = join ', ', @$_ foreach values %$errors;
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
$verify_uri->query_form({email => $params->{email}});
Email::Stuffer->from('noreply@' . $c->stash->{instance})
->to($params->{email})
->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
->text_body(
"Durch Klick auf folgenden Link bestätigen Sie die Anmeldung und, dass Sie
untenstehende Regeln akzeptieren:\n\n"
. $verify_uri
. "\n\n" . $c->config->{registration_rules}
)
->send;
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
sub check_email_whitelist {
my ($self, $c, $params) = @_;
my $whitelist = $c->config->{registration_email_whitelist}
or return;
my %whitelist = map { $_ => 1 } @$whitelist;
return if $whitelist{$params->{email}};
return { email => ['Emailadresse nicht in der Mitgliederliste'] };
}
sub check_duplicates {
my ($self, $c, $params) = @_;
my $username = $params->{username};
my $context = $c->stash->{context};
my $unverified = $context->attribute('children')->filtered(username => $username);
- my $registered = $context->parent->attribute('children')->filtered(username => $username);
+ my $registered = $self->list($c)->attribute('children')->filtered(username => $username);
return { username => ['bereits vergeben'] } if @$unverified or @$registered;
}
sub verify : CiderCMS('verify_registration') {
my ( $self, $c ) = @_;
my $users = $c->stash->{context}->attribute('children')->filtered(
email => $c->req->params->{email}
);
die "No user found for " . $c->req->params->{email} unless @$users;
my $user = $users->[0];
- $user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
+ $user->move_to(parent => $self->list($c), parent_attr => 'children');
return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
}
+sub list {
+ my ($self, $c) = @_;
+
+ return $c->stash->{context}->object_by_id($c->stash->{context}->property('list'));
+}
+
1;
diff --git a/t/custom_registration.t b/t/custom_registration.t
index a4e8941..e776bf5 100644
--- a/t/custom_registration.t
+++ b/t/custom_registration.t
@@ -1,302 +1,308 @@
use strict;
use warnings;
use utf8;
use Test::More;
BEGIN { $ENV{EMAIL_SENDER_TRANSPORT} = 'Test' }
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use FindBin qw($Bin);
use Regexp::Common qw(URI);
my ($root, $users, $restricted);
setup_test_instance();
test_registration_not_offered();
setup_registration_objects();
test_registration();
done_testing;
sub setup_test_instance {
setup_types();
setup_objects();
}
sub setup_types {
setup_folder_type();
setup_textarea_type();
setup_userlist_type();
setup_user_type();
setup_registration_type();
}
sub setup_folder_type {
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
template => 'folder.zpt',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'restricted',
data_type => 'Boolean',
default_value => 0,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_textarea_type {
CiderCMS::Test->populate_types({
textarea => {
name => 'Textarea',
template => 'textarea.zpt',
page_element => 1,
attributes => [
{
id => 'text',
mandatory => 1,
},
],
},
});
}
sub setup_userlist_type {
CiderCMS::Test->populate_types({
userlist => {
name => 'User list',
attributes => [{
type => 'userlist',
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_user_type {
CiderCMS::Test->populate_types({
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'email',
data_type => 'String',
mandatory => 1,
},
],
},
});
CiderCMS::Test->write_template('user', q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>));
}
sub setup_objects {
$root = $model->get_object($c, 1);
$users = $root->create_child(
attribute => 'children',
type => 'userlist',
data => { title => 'Users' },
);
$restricted = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Restricted', restricted => 1 },
);
}
sub setup_registration_type {
CiderCMS::Test->populate_types({
registration => {
name => 'Registration',
template => 'registration.zpt',
attributes => [
+ {
+ id => 'list',
+ data_type => 'Integer',
+ },
{
id => 'children',
data_type => 'Object',
},
{
id => 'success',
data_type => 'Object',
},
{
id => 'verified',
data_type => 'Object',
},
],
},
});
$model->create_attribute($c, {
type => 'userlist',
id => 'registration',
name => 'Registration',
sort_id => 0,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => '',
});
}
sub setup_registration_objects {
my $registration = $users->create_child(
attribute => 'registration',
type => 'registration',
- data => {},
+ data => {
+ list => $users->{id},
+ },
);
my $success = $registration->create_child(
attribute => 'success',
type => 'folder',
data => { title => 'Success' },
);
$success->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! Please check your email.' },
);
my $verified = $registration->create_child(
attribute => 'verified',
type => 'folder',
data => { title => 'Verified' },
);
$verified->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! You are now registered.' },
);
}
sub test_registration_not_offered {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_lacks('Neuen Benutzer registrieren');
}
sub test_registration {
start_registration();
test_validation();
test_success();
test_duplicate();
}
sub start_registration {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_contains('Neuen Benutzer registrieren');
$mech->follow_link_ok({text => 'Neuen Benutzer registrieren'});
}
sub test_validation {
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_contains('missing');
$mech->submit_form_ok({
with_fields => {
password => 'testpass',
email => '[email protected]',
},
});
$mech->content_contains('Emailadresse nicht in der Mitgliederliste');
$mech->submit_form_ok({
with_fields => {
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
}
sub test_success {
my @deliveries = Email::Sender::Simple->default_transport->deliveries;
is(scalar @deliveries, 1, 'Confirmation message sent');
my $envelope = $deliveries[0]->{envelope};
is_deeply($envelope->{to}, ['test@localhost'], 'Confirmation message recipient correct');
is($envelope->{from}, "noreply\@$instance", 'Confirmation message sender correct');
my $email = $deliveries[0]->{email};
is(
$email->get_header("Subject"),
"Bestätigung der Anmeldung zu $instance",
'Confirmation message subject correct'
);
my ($link) = $email->get_body =~ /($RE{URI}{HTTP})/;
$mech->get_ok($link);
$mech->content_lacks('Login');
$mech->content_contains('Success! You are now registered.');
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_lacks('Login');
$mech->content_lacks('Invalid username/password');
$mech->title_is('Restricted');
}
sub test_duplicate {
$mech->get_ok("http://localhost/system/logout");
start_registration();
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('bereits vergeben', 'duplicate registered found');
$mech->submit_form_ok({
with_fields => {
username => 'testname2',
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
start_registration();
$mech->submit_form_ok({
with_fields => {
username => 'testname2',
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('bereits vergeben', 'duplicate unverified found');
}
|
niner/CiderCMS
|
e2dd3f08af8c12c43f5778c915e67854ff9e5426
|
Script to clean up holes in sort_ids
|
diff --git a/lib/CiderCMS/Model/DB.pm b/lib/CiderCMS/Model/DB.pm
index fd6f6f8..4b07ea9 100644
--- a/lib/CiderCMS/Model/DB.pm
+++ b/lib/CiderCMS/Model/DB.pm
@@ -1,559 +1,576 @@
package CiderCMS::Model::DB;
use strict;
use warnings;
use base 'Catalyst::Model::DBI';
use File::Slurp qw(read_file);
use File::Path qw(make_path);
use Carp qw(croak cluck confess);
use English '-no_match_vars';
use Digest::SHA qw(sha256_hex);
use CiderCMS::Object;
__PACKAGE__->config(
dsn => 'dbi:Pg:dbname=cidercms',
user => '',
password => '',
options => {
pg_enable_utf8 => 1,
quote_char => '"',
name_sep => '.',
},
);
=head1 NAME
CiderCMS::Model::DB - DBI Model Class
=head1 METHODS
=head2 create_instance($c, {id => 'test.example', title => 'Testsite'})
Creates a new instance including schema and instance directory
=cut
sub create_instance {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
my $instance_path = $c->config->{root} . '/instances/' . $data->{id};
mkdir "$instance_path$_" foreach '', qw( /static /templates /templates/layout /templates/content );
$dbh->do(qq(create schema "$data->{id}")) or croak qq(could not create schema "$data->{id}");
$dbh->do(qq(set search_path="$data->{id}",public)) or croak qq(could not set search path "$data->{id}",public!?);
$dbh->do(scalar read_file($c->config->{root} . '/initial_schema.sql')) or croak 'could not import initial schema';
$c->stash({instance => $data->{id}});
$self->create_type($c, {id => 'site', name => 'Site', page_element => 0});
$self->create_attribute($c, {type => 'site', id => 'title', name => 'Title', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''});
$self->create_attribute($c, {type => 'site', id => 'publish_uri', name => 'Publishing target URI', sort_id => 2, data_type => 'String', repetitive => 0, mandatory => 0, default_value => ''});
$self->create_attribute($c, {type => 'site', id => 'children', name => 'Children', sort_id => 1, data_type => 'Object', repetitive => 1, mandatory => 0, default_value => ''});
$self->initialize($c);
CiderCMS::Object->new({c => $c, type => 'site', dcid => '', data => {title => $data->{title}}})->insert;
return;
}
=head2 instance_exists($instance)
Returns true if an instance with the given name exists in the database.
=cut
sub instance_exists {
my ($self, $instance) = @_;
return $self->dbh->selectrow_array("
select count(*)
from pg_namespace
where
nspowner != 10
and nspname != 'public'
and nspname = ?
",
undef,
$instance
);
}
=head2 initialize($c)
Fetches type and attribute information from the DB and puts it on the stash:
types => {
type1 => {
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
}
Should be called after every change to the schema.
=cut
sub initialize {
my ($self, $c) = @_;
my $dbh = $self->dbh;
my $instance = $c->stash->{instance};
confess 'You did not set $c->stash->{instance} before calling initialize!' unless $instance;
return unless $self->instance_exists($instance);
$dbh->do(qq(set search_path="$instance",public))
or croak qq(could not set search path "$instance",public);
my $types = $dbh->selectall_arrayref('select * from sys_types', {Slice => {}});
my $attrs = $dbh->selectall_arrayref('select * from sys_attributes order by sort_id', {Slice => {}});
my %types = map { $_->{id} => { %$_, attributes => [], attr => {} } } @$types;
foreach (@$attrs) {
push @{ $types{$_->{type}}{attributes} }, $_;
$types{$_->{type}}{attr}{$_->{id}} = $_;
$_->{class} = "CiderCMS::Attribute::$_->{data_type}";
}
$c->stash({
types => \%types,
});
return 1;
}
=head2 traverse_path($c, $path)
Traverses a path (given as hashref) and returns the objects found
=cut
sub traverse_path {
my ($self, $c, $path) = @_;
my @objects;
my $object;
my $dbh = $self->dbh;
my $level = 0;
foreach (@$path) {
my $may_be_id = /\A\d+\z/xm;
$object = $dbh->selectrow_hashref(
'select id, type from sys_object where parent '
. (@objects ? ' = ?' : ' is null')
. ' and ' . ($may_be_id ? '(id=? or dcid=?)' : 'dcid=?'),
undef,
(@objects ? $objects[-1]->{id} : ()),
$_,
($may_be_id ? $_ : ()),
) or croak qq{node "$_" not found\n};
$object->{level} = $level++;
push @objects, $self->inflate_object($c, $object);
}
return @objects;
}
=head2 get_object($c, $id, $level)
Returns a content object for the given ID.
Sets the object's level to the given $level
=cut
#TODO great point to add some caching
sub get_object {
my ($self, $c, $id, $level) = @_;
$level ||= 0;
my $object = $self->dbh->selectrow_hashref('select id, type from sys_object where id = ?', undef, $id);
$object->{level} = $level;
return $self->inflate_object($c, $object);
}
=head2 inflate_object($c, $object)
Takes a stub object (consisting of id, type and level information) and inflates it to a full blown and initialized CiderCMS::Object.
=cut
sub inflate_object {
my ($self, $c, $object) = @_;
my $level = $object->{level};# or $object->{type} ne 'site' and cluck "$object->{type} has no level!";
$object = $self->dbh->selectrow_hashref(qq(select * from "$object->{type}" where id=?), undef, $object->{id});
return CiderCMS::Object->new({c => $c, id => $object->{id}, type => $object->{type}, dcid => $object->{dcid}, parent => $object->{parent}, parent_attr => $object->{parent_attr}, level => $level, sort_id => $object->{sort_id}, data => $object});
}
=head2 object_children($c, $object, $attr)
Returns the children of an object as list in list context and as array ref in scalar context.
=cut
sub object_children {
my ($self, $c, $object, $attr) = @_;
my @children = map {
$self->inflate_object($c, {%$_, level => $object->{level} + 1});
} @{ $self->dbh->selectall_arrayref('select id, type from sys_object where parent = ?' . ($attr ? ' and parent_attr = ?' : '') . ' order by sort_id', {Slice => {}}, $object->{id}, ($attr ? $attr : ())) };
return wantarray ? @children : \@children;
}
=head2 create_type($c, {id => 'type1', name => 'Type 1', page_element => 0})
Creates a new type by creating a database table for it and an entry in the sys_types table.
=cut
sub create_type {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
my $id = $data->{id};
$data->{page_element} ||= 0;
$self->txn_do(sub {
$dbh->do('insert into sys_types (id, name, page_element) values (?, ?, ?)', undef, $id, $data->{name}, $data->{page_element});
$dbh->do(q/set client_min_messages='warning'/); # avoid the CREATE TABLE / PRIMARY KEY will create implicit index NOTICE
$dbh->do(qq/create table "$id" (id integer not null, parent integer, parent_attr varchar, sort_id integer default 0 not null, type varchar not null references sys_types (id) default '$id', changed timestamp not null default now(), tree_changed timestamp not null default now(), active_start timestamp, active_end timestamp, dcid varchar)/);
$dbh->do(q/set client_min_messages='notice'/); # back to full information
$dbh->do(qq/create trigger "${id}_bi" before insert on "$id" for each row execute procedure sys_objects_bi()/);
$dbh->do(qq/create trigger "${id}_bu" before update on "$id" for each row execute procedure sys_objects_bu()/);
$dbh->do(qq/create trigger "${id}_ad" after delete on "$id" for each row execute procedure sys_objects_ad()/);
});
my $path = $c->fs_path_for_instance . '/../templates/types';
unless (-e "$path/$data->{id}.zpt" or -e $c->config->{root} . "/templates/types/$data->{id}.zpt") { #TODO: put this stuff in it's own class. CiderCMS::Type?
make_path($path);
open my $template, '>', "$path/$data->{id}.zpt" or croak "Could not open $path/$data->{id}.zpt: $OS_ERROR";
say { $template } '<div xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS" tal:attributes="id string:object_${self/id}" />';
close $template;
}
$self->initialize($c);
return;
}
=head2 update_type($c, $id, {id => 'type1', name => 'Type 1', page_element => 0})
Updates an existing type.
=cut
sub update_type {
my ($self, $c, $id, $data) = @_;
my $dbh = $self->dbh;
$data->{page_element} ||= 0;
if ($data->{id} ne $id) {
$self->txn_do(sub {
$dbh->do('set constraints "sys_attributes_type_fkey" deferred');
$dbh->do('update sys_types set id = ?, name = ?, page_element = ? where id = ?', undef, @$data{qw(id name page_element)}, $id);
$dbh->do(q/update sys_attributes set type = ? where type = ?/, undef, $data->{id}, $id);
$dbh->do(qq/alter table "$id" rename to "$data->{id}"/);
});
}
else {
$dbh->do('update sys_types set id = ?, name = ?, page_element = ? where id = ?', undef, @$data{qw(id name page_element)}, $id);
}
return;
}
=head2 create_attribute($c, {type => 'type1', id => 'attr1', name => 'Attribute 1', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''})
Adds a new attribute to a type by creating the column in the type's table and an entry in the sys_attributes table.
=cut
sub create_attribute {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
$_ = $_ ? 1 : 0 foreach @$data{qw(mandatory repetitive)};
$self->txn_do(sub {
$dbh->do('insert into sys_attributes (type, id, name, data_type, repetitive, mandatory, default_value) values (?, ?, ?, ?, ?, ?, ?)', undef, @$data{qw(type id name data_type repetitive mandatory default_value)});
if (my $data_type = "CiderCMS::Attribute::$data->{data_type}"->db_type) {
my $query = qq/alter table "$data->{type}" add column "$data->{id}" $data_type/;
$query .= ' not null' if $data->{mandatory};
$query .= ' default ' . $dbh->quote($data->{default}) if defined $data->{default} and $data->{default} ne '';
$dbh->do($query);
}
});
$self->initialize($c);
return;
}
=head2 update_attribute($c, {type => 'type1', id => 'attr1', name => 'Attribute 1', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''})
Updates an existing attribute.
=cut
sub update_attribute {
my ($self, $c, $type, $id, $data) = @_;
my $dbh = $self->dbh;
$_ = $_ ? 1 : 0 foreach @$data{qw(mandatory repetitive)};
$self->txn_do(sub {
$dbh->do('update sys_attributes set id = ?, sort_id = ?, name = ?, data_type = ?, repetitive = ?, mandatory = ?, default_value = ? where type = ? and id = ?', undef, @$data{qw(id sort_id name data_type repetitive mandatory default_value)}, $type, $id);
});
return;
}
=head2 create_insert_aisle({c => $c, parent => $parent, attr => $attr, count => $count, after => $after})
Creates an aisle in the sort order of an object's children to insert new objects in between.
=cut
sub create_insert_aisle {
my ($self, $params) = @_;
my $dbh = $self->dbh;
if ($params->{after}) {
$params->{after} = $self->get_object($params->{c}, $params->{after}) unless ref $params->{after};
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('update sys_object set sort_id = -sort_id where parent = ? and parent_attr = ? and sort_id > ?', undef, $params->{parent}, $params->{attr}, $params->{after}->{sort_id});
$dbh->do("update sys_object set sort_id = -sort_id + $params->{count} where parent = ? and parent_attr = ? and sort_id < 0", undef, $params->{parent}, $params->{attr});
return $params->{after}->{sort_id} + 1;
}
else {
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('update sys_object set sort_id = -sort_id where parent = ? and parent_attr = ?', undef, $params->{parent}, $params->{attr});
$dbh->do("update sys_object set sort_id = -sort_id + $params->{count} where parent = ? and parent_attr = ?", undef, $params->{parent}, $params->{attr});
return 1;
}
}
=head2 close_aisle($c, $parent, $attr, $sort_id)
Closes an aisle in the sort order of an object's children after removing a child.
=cut
sub close_aisle {
my ($self, $c, $parent, $attr, $sort_id) = @_;
my $dbh = $self->dbh;
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('
update sys_object
set sort_id = -sort_id
where parent = ? and parent_attr = ? and sort_id > ?
',
undef,
$parent->{id},
$attr,
$sort_id,
);
$dbh->do('
update sys_object
set sort_id = -sort_id - 1
where parent = ? and parent_attr = ? and sort_id < ?
',
undef,
$parent->{id},
$attr,
-$sort_id,
);
return;
}
=head2 insert_object($c, $object)
Inserts a CiderCMS::Object into the database.
=cut
my @sys_object_columns = qw(id parent parent_attr sort_id type active_start active_end dcid);
sub insert_object {
my ($self, $c, $object, $params) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
local $dbh->{RaiseError} = 1;
return $self->txn_do(sub {
$object->{sort_id} = $self->create_insert_aisle({c => $c, parent => $object->{parent}, attr => $object->{parent_attr}, count => 1, after => $params->{after}});
my ($columns, $values) = $object->get_dirty_columns(); # DBIx::Class::Row yeah
my $insert_statement = qq{insert into "$type" (} . join (q{, }, map { qq{"$_"} } @sys_object_columns, @$columns) . ') values (' . join (q{, }, map { '?' } @sys_object_columns, @$columns) . ')';
if (my $retval = $dbh->do($insert_statement, undef, (map { $object->{$_} } @sys_object_columns), @$values)) {
$object->{id} = $dbh->last_insert_id(undef, undef, 'sys_object', undef, {sequence => 'sys_object_id_seq'});
return $retval;
}
});
}
=head2 update_object($c, $object)
Updates a CiderCMS::Object in the database.
=cut
sub update_object {
my ($self, $c, $object) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
my ($columns, $values) = $object->get_dirty_columns(); # DBIx::Class::Row yeah
my $update_statement = qq{update "$type" set } . join (q{, }, map { qq{"$_" = ?} } @sys_object_columns, @$columns) . ' where id = ?';
if (my $retval = $dbh->do($update_statement, undef, (map { $object->{$_} } @sys_object_columns), @$values, $object->{id})) {
return $retval;
}
else {
croak $dbh->errstr;
}
}
=head2 delete_object($c, $object)
Deletes a CiderCMS::Object from the database.
=cut
sub delete_object {
my ($self, $c, $object) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
if (my $retval = $dbh->do(qq{delete from "$type" where id = ?}, undef, $object->{id})) {
$self->close_aisle($c, $object->parent, $object->{parent_attr}, $object->{sort_id});
return $retval;
}
else {
croak $dbh->errstr;
}
}
=head2 move_object($c, $object, $params)
Moves a CiderCMS::Object to a new parent and or sort position
=cut
sub move_object {
my ($self, $c, $object, $params) = @_;
my ($old_parent, $old_parent_attr, $old_sort_id);
if ($params->{parent} and $params->{parent} != $object->{parent} or $params->{parent_attr} and $params->{parent_attr} ne $object->{parent_attr}) {
$old_parent = $object->parent;
$old_parent_attr = $object->{parent_attr};
$old_sort_id = $object->{sort_id};
$object->{parent} = $params->{parent}{id};
$object->{parent_attr} = $params->{parent_attr};
}
$object->{sort_id} = $self->create_insert_aisle({c => $c, parent => $object->{parent}, attr => $object->{parent_attr}, count => 1, after => $params->{after}});
my $result = $self->update_object($c, $object);
if ($old_parent) {
$self->close_aisle($c, $old_parent, $old_parent_attr, $old_sort_id);
}
return $result;
}
+=head2 instances()
+
+Returns a list of all instances.
+
+=cut
+
+sub instances {
+ my ($self) = @_;
+
+ return $self->dbh->selectcol_arrayref(q[
+ select nspname
+ from pg_namespace
+ where nspowner != 10 and nspname != 'public'
+ order by nspname
+ ]);
+}
+
=head2 txn_do($code)
Run $sub in a transaction. Rollback transaction if $sub dies.
=cut
sub txn_do {
my ($self, $code) = @_;
my $dbh = $self->dbh;
my $in_txn = not $dbh->{AutoCommit};
$dbh->begin_work unless $in_txn;
my ($result, @results);
if (wantarray) {
@results = $code->();
}
else {
$result = $code->();
}
$dbh->commit unless $in_txn or $dbh->{AutoCommit};
return wantarray ? @results : $result;
}
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
DBI Model Class.
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/script/clean_sort_ids.pl b/script/clean_sort_ids.pl
new file mode 100644
index 0000000..f71fc43
--- /dev/null
+++ b/script/clean_sort_ids.pl
@@ -0,0 +1,43 @@
+use 5.14.0;
+use warnings;
+use utf8;
+use FindBin qw($Bin);
+use lib "$Bin/../lib";
+
+use CiderCMS::Test;
+my $c = CiderCMS::Test::context;
+
+my $model = $c->model('DB');
+my $dbh = $model->dbh;
+
+foreach my $instance (@{ $model->instances }) {
+ say $instance;
+ $model->txn_do(sub {
+ $dbh->do("set search_path=?", undef, $instance);
+ my $sys_object = $dbh->quote_identifier(undef, $instance, 'sys_object');
+ my $objects = $dbh->selectall_arrayref(
+ "select * from $sys_object where parent is not null order by parent, parent_attr, sort_id",
+ {Slice => {}},
+ );
+ my $parent = 0;
+ my $parent_attr = '';
+ my $sort_id;
+ foreach my $object (@$objects) {
+ if ($parent != $object->{parent} or $parent_attr ne $object->{parent_attr}) {
+ $sort_id = 0;
+ $parent = $object->{parent};
+ $parent_attr = $object->{parent_attr};
+ }
+ $sort_id++;
+ if ($object->{sort_id} != $sort_id) {
+ say "$object->{parent}/$object->{parent_attr}: $object->{sort_id} => $sort_id";
+ $dbh->do(
+ "update $sys_object set sort_id = ? where id = ?",
+ undef,
+ $sort_id,
+ $object->{id},
+ );
+ }
+ }
+ });
+}
|
niner/CiderCMS
|
0ffa7bf97a0d61cdb53c4186e76c0a7f3b4e9a63
|
More tests for sort_ids
|
diff --git a/t/paste.t b/t/paste.t
index 5bbfff6..d9e9582 100644
--- a/t/paste.t
+++ b/t/paste.t
@@ -1,75 +1,106 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
attributes => [
{
id => 'title',
data_type => 'Title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
mandatory => 0,
},
],
},
textfield => {
name => 'Textfield',
attributes => [
{
id => 'text',
data_type => 'Text',
mandatory => 1,
},
],
},
});
my $root = $model->get_object($c, 1);
my $source = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Source' },
);
my @texts = reverse map {
$source->create_child(
attribute => 'children',
type => 'textfield',
data => {
text => "$_",
},
);
} reverse 1 .. 10;
my $destination = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Destination' },
);
-$_->refresh foreach @texts;
-is_deeply [ map { $_->{sort_id} } @texts ], [ 1 .. @texts ];
+source_in_order();
+# move #1 text from source to destination
my $moving = shift @texts;
$moving->move_to(parent => $destination, parent_attr => 'children');
my @moved = $moving;
$_->refresh foreach @texts;
is_deeply [ map { $_->{sort_id} } @texts ], [ 1 .. @texts ];
is($moving->refresh->{sort_id}, 1);
+source_in_order();
+# move #3 text from source to destination
($moving) = splice @texts, 1, 1;
$moving->move_to(parent => $destination, parent_attr => 'children');
push @moved, $moving;
+source_in_order();
$_->refresh foreach @moved;
is_deeply [ map { $_->{sort_id} } @moved ], [2, 1];
+# move #5 text from source to destination after first
+($moving) = splice @texts, 2, 1;
+$moving->move_to(parent => $destination, parent_attr => 'children', after => $moved[1]);
+push @moved, $moving;
+source_in_order();
+
+$_->refresh foreach @moved;
+is_deeply [ map { $_->{sort_id} } @moved ], [3, 1, 2];
+
+# move last text from source to destination after last
+($moving) = pop @texts;
+$moving->move_to(parent => $destination, parent_attr => 'children', after => $moved[0]);
+push @moved, $moving;
+source_in_order();
+
+$_->refresh foreach @moved;
+is_deeply [ map { $_->{sort_id} } @moved ], [3, 1, 2, 4];
+
+is_deeply [ map { $_->property('text') } @moved ], [1, 3, 5, 10], 'sanity check moved texts';
+
done_testing;
+
+sub source_in_order {
+ $_->refresh foreach @texts;
+ is_deeply
+ [ map { $_->{sort_id} } @texts ],
+ [ 1 .. @texts ],
+ @texts . ' source texts have correct sort_id';
+}
|
niner/CiderCMS
|
2264afeae9cbd4ea95d55c4b8ea7bdb84b35cdf9
|
Fix unique key violations on paste
|
diff --git a/lib/CiderCMS/Model/DB.pm b/lib/CiderCMS/Model/DB.pm
index ff36a2b..fd6f6f8 100644
--- a/lib/CiderCMS/Model/DB.pm
+++ b/lib/CiderCMS/Model/DB.pm
@@ -1,539 +1,559 @@
package CiderCMS::Model::DB;
use strict;
use warnings;
use base 'Catalyst::Model::DBI';
use File::Slurp qw(read_file);
use File::Path qw(make_path);
use Carp qw(croak cluck confess);
use English '-no_match_vars';
use Digest::SHA qw(sha256_hex);
use CiderCMS::Object;
__PACKAGE__->config(
dsn => 'dbi:Pg:dbname=cidercms',
user => '',
password => '',
options => {
pg_enable_utf8 => 1,
quote_char => '"',
name_sep => '.',
},
);
=head1 NAME
CiderCMS::Model::DB - DBI Model Class
=head1 METHODS
=head2 create_instance($c, {id => 'test.example', title => 'Testsite'})
Creates a new instance including schema and instance directory
=cut
sub create_instance {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
my $instance_path = $c->config->{root} . '/instances/' . $data->{id};
mkdir "$instance_path$_" foreach '', qw( /static /templates /templates/layout /templates/content );
$dbh->do(qq(create schema "$data->{id}")) or croak qq(could not create schema "$data->{id}");
$dbh->do(qq(set search_path="$data->{id}",public)) or croak qq(could not set search path "$data->{id}",public!?);
$dbh->do(scalar read_file($c->config->{root} . '/initial_schema.sql')) or croak 'could not import initial schema';
$c->stash({instance => $data->{id}});
$self->create_type($c, {id => 'site', name => 'Site', page_element => 0});
$self->create_attribute($c, {type => 'site', id => 'title', name => 'Title', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''});
$self->create_attribute($c, {type => 'site', id => 'publish_uri', name => 'Publishing target URI', sort_id => 2, data_type => 'String', repetitive => 0, mandatory => 0, default_value => ''});
$self->create_attribute($c, {type => 'site', id => 'children', name => 'Children', sort_id => 1, data_type => 'Object', repetitive => 1, mandatory => 0, default_value => ''});
$self->initialize($c);
CiderCMS::Object->new({c => $c, type => 'site', dcid => '', data => {title => $data->{title}}})->insert;
return;
}
=head2 instance_exists($instance)
Returns true if an instance with the given name exists in the database.
=cut
sub instance_exists {
my ($self, $instance) = @_;
return $self->dbh->selectrow_array("
select count(*)
from pg_namespace
where
nspowner != 10
and nspname != 'public'
and nspname = ?
",
undef,
$instance
);
}
=head2 initialize($c)
Fetches type and attribute information from the DB and puts it on the stash:
types => {
type1 => {
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
}
Should be called after every change to the schema.
=cut
sub initialize {
my ($self, $c) = @_;
my $dbh = $self->dbh;
my $instance = $c->stash->{instance};
confess 'You did not set $c->stash->{instance} before calling initialize!' unless $instance;
return unless $self->instance_exists($instance);
$dbh->do(qq(set search_path="$instance",public))
or croak qq(could not set search path "$instance",public);
my $types = $dbh->selectall_arrayref('select * from sys_types', {Slice => {}});
my $attrs = $dbh->selectall_arrayref('select * from sys_attributes order by sort_id', {Slice => {}});
my %types = map { $_->{id} => { %$_, attributes => [], attr => {} } } @$types;
foreach (@$attrs) {
push @{ $types{$_->{type}}{attributes} }, $_;
$types{$_->{type}}{attr}{$_->{id}} = $_;
$_->{class} = "CiderCMS::Attribute::$_->{data_type}";
}
$c->stash({
types => \%types,
});
return 1;
}
=head2 traverse_path($c, $path)
Traverses a path (given as hashref) and returns the objects found
=cut
sub traverse_path {
my ($self, $c, $path) = @_;
my @objects;
my $object;
my $dbh = $self->dbh;
my $level = 0;
foreach (@$path) {
my $may_be_id = /\A\d+\z/xm;
$object = $dbh->selectrow_hashref(
'select id, type from sys_object where parent '
. (@objects ? ' = ?' : ' is null')
. ' and ' . ($may_be_id ? '(id=? or dcid=?)' : 'dcid=?'),
undef,
(@objects ? $objects[-1]->{id} : ()),
$_,
($may_be_id ? $_ : ()),
) or croak qq{node "$_" not found\n};
$object->{level} = $level++;
push @objects, $self->inflate_object($c, $object);
}
return @objects;
}
=head2 get_object($c, $id, $level)
Returns a content object for the given ID.
Sets the object's level to the given $level
=cut
#TODO great point to add some caching
sub get_object {
my ($self, $c, $id, $level) = @_;
$level ||= 0;
my $object = $self->dbh->selectrow_hashref('select id, type from sys_object where id = ?', undef, $id);
$object->{level} = $level;
return $self->inflate_object($c, $object);
}
=head2 inflate_object($c, $object)
Takes a stub object (consisting of id, type and level information) and inflates it to a full blown and initialized CiderCMS::Object.
=cut
sub inflate_object {
my ($self, $c, $object) = @_;
my $level = $object->{level};# or $object->{type} ne 'site' and cluck "$object->{type} has no level!";
$object = $self->dbh->selectrow_hashref(qq(select * from "$object->{type}" where id=?), undef, $object->{id});
return CiderCMS::Object->new({c => $c, id => $object->{id}, type => $object->{type}, dcid => $object->{dcid}, parent => $object->{parent}, parent_attr => $object->{parent_attr}, level => $level, sort_id => $object->{sort_id}, data => $object});
}
=head2 object_children($c, $object, $attr)
Returns the children of an object as list in list context and as array ref in scalar context.
=cut
sub object_children {
my ($self, $c, $object, $attr) = @_;
my @children = map {
$self->inflate_object($c, {%$_, level => $object->{level} + 1});
} @{ $self->dbh->selectall_arrayref('select id, type from sys_object where parent = ?' . ($attr ? ' and parent_attr = ?' : '') . ' order by sort_id', {Slice => {}}, $object->{id}, ($attr ? $attr : ())) };
return wantarray ? @children : \@children;
}
=head2 create_type($c, {id => 'type1', name => 'Type 1', page_element => 0})
Creates a new type by creating a database table for it and an entry in the sys_types table.
=cut
sub create_type {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
my $id = $data->{id};
$data->{page_element} ||= 0;
$self->txn_do(sub {
$dbh->do('insert into sys_types (id, name, page_element) values (?, ?, ?)', undef, $id, $data->{name}, $data->{page_element});
$dbh->do(q/set client_min_messages='warning'/); # avoid the CREATE TABLE / PRIMARY KEY will create implicit index NOTICE
$dbh->do(qq/create table "$id" (id integer not null, parent integer, parent_attr varchar, sort_id integer default 0 not null, type varchar not null references sys_types (id) default '$id', changed timestamp not null default now(), tree_changed timestamp not null default now(), active_start timestamp, active_end timestamp, dcid varchar)/);
$dbh->do(q/set client_min_messages='notice'/); # back to full information
$dbh->do(qq/create trigger "${id}_bi" before insert on "$id" for each row execute procedure sys_objects_bi()/);
$dbh->do(qq/create trigger "${id}_bu" before update on "$id" for each row execute procedure sys_objects_bu()/);
$dbh->do(qq/create trigger "${id}_ad" after delete on "$id" for each row execute procedure sys_objects_ad()/);
});
my $path = $c->fs_path_for_instance . '/../templates/types';
unless (-e "$path/$data->{id}.zpt" or -e $c->config->{root} . "/templates/types/$data->{id}.zpt") { #TODO: put this stuff in it's own class. CiderCMS::Type?
make_path($path);
open my $template, '>', "$path/$data->{id}.zpt" or croak "Could not open $path/$data->{id}.zpt: $OS_ERROR";
say { $template } '<div xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS" tal:attributes="id string:object_${self/id}" />';
close $template;
}
$self->initialize($c);
return;
}
=head2 update_type($c, $id, {id => 'type1', name => 'Type 1', page_element => 0})
Updates an existing type.
=cut
sub update_type {
my ($self, $c, $id, $data) = @_;
my $dbh = $self->dbh;
$data->{page_element} ||= 0;
if ($data->{id} ne $id) {
$self->txn_do(sub {
$dbh->do('set constraints "sys_attributes_type_fkey" deferred');
$dbh->do('update sys_types set id = ?, name = ?, page_element = ? where id = ?', undef, @$data{qw(id name page_element)}, $id);
$dbh->do(q/update sys_attributes set type = ? where type = ?/, undef, $data->{id}, $id);
$dbh->do(qq/alter table "$id" rename to "$data->{id}"/);
});
}
else {
$dbh->do('update sys_types set id = ?, name = ?, page_element = ? where id = ?', undef, @$data{qw(id name page_element)}, $id);
}
return;
}
=head2 create_attribute($c, {type => 'type1', id => 'attr1', name => 'Attribute 1', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''})
Adds a new attribute to a type by creating the column in the type's table and an entry in the sys_attributes table.
=cut
sub create_attribute {
my ($self, $c, $data) = @_;
my $dbh = $self->dbh;
$_ = $_ ? 1 : 0 foreach @$data{qw(mandatory repetitive)};
$self->txn_do(sub {
$dbh->do('insert into sys_attributes (type, id, name, data_type, repetitive, mandatory, default_value) values (?, ?, ?, ?, ?, ?, ?)', undef, @$data{qw(type id name data_type repetitive mandatory default_value)});
if (my $data_type = "CiderCMS::Attribute::$data->{data_type}"->db_type) {
my $query = qq/alter table "$data->{type}" add column "$data->{id}" $data_type/;
$query .= ' not null' if $data->{mandatory};
$query .= ' default ' . $dbh->quote($data->{default}) if defined $data->{default} and $data->{default} ne '';
$dbh->do($query);
}
});
$self->initialize($c);
return;
}
=head2 update_attribute($c, {type => 'type1', id => 'attr1', name => 'Attribute 1', sort_id => 0, data_type => 'String', repetitive => 0, mandatory => 1, default_value => ''})
Updates an existing attribute.
=cut
sub update_attribute {
my ($self, $c, $type, $id, $data) = @_;
my $dbh = $self->dbh;
$_ = $_ ? 1 : 0 foreach @$data{qw(mandatory repetitive)};
$self->txn_do(sub {
$dbh->do('update sys_attributes set id = ?, sort_id = ?, name = ?, data_type = ?, repetitive = ?, mandatory = ?, default_value = ? where type = ? and id = ?', undef, @$data{qw(id sort_id name data_type repetitive mandatory default_value)}, $type, $id);
});
return;
}
=head2 create_insert_aisle({c => $c, parent => $parent, attr => $attr, count => $count, after => $after})
Creates an aisle in the sort order of an object's children to insert new objects in between.
=cut
sub create_insert_aisle {
my ($self, $params) = @_;
my $dbh = $self->dbh;
if ($params->{after}) {
$params->{after} = $self->get_object($params->{c}, $params->{after}) unless ref $params->{after};
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('update sys_object set sort_id = -sort_id where parent = ? and parent_attr = ? and sort_id > ?', undef, $params->{parent}, $params->{attr}, $params->{after}->{sort_id});
$dbh->do("update sys_object set sort_id = -sort_id + $params->{count} where parent = ? and parent_attr = ? and sort_id < 0", undef, $params->{parent}, $params->{attr});
return $params->{after}->{sort_id} + 1;
}
else {
# ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
$dbh->do('update sys_object set sort_id = -sort_id where parent = ? and parent_attr = ?', undef, $params->{parent}, $params->{attr});
$dbh->do("update sys_object set sort_id = -sort_id + $params->{count} where parent = ? and parent_attr = ?", undef, $params->{parent}, $params->{attr});
return 1;
}
}
=head2 close_aisle($c, $parent, $attr, $sort_id)
Closes an aisle in the sort order of an object's children after removing a child.
=cut
sub close_aisle {
my ($self, $c, $parent, $attr, $sort_id) = @_;
my $dbh = $self->dbh;
- $dbh->do('update sys_object set sort_id = sort_id - 1 where parent = ? and parent_attr = ? and sort_id > ?', undef, $parent->{id}, $attr, $sort_id);
+ # ugly hack to prevent PostgreSQL from complaining about a violated unique constraint:
+ $dbh->do('
+ update sys_object
+ set sort_id = -sort_id
+ where parent = ? and parent_attr = ? and sort_id > ?
+ ',
+ undef,
+ $parent->{id},
+ $attr,
+ $sort_id,
+ );
+ $dbh->do('
+ update sys_object
+ set sort_id = -sort_id - 1
+ where parent = ? and parent_attr = ? and sort_id < ?
+ ',
+ undef,
+ $parent->{id},
+ $attr,
+ -$sort_id,
+ );
return;
}
=head2 insert_object($c, $object)
Inserts a CiderCMS::Object into the database.
=cut
my @sys_object_columns = qw(id parent parent_attr sort_id type active_start active_end dcid);
sub insert_object {
my ($self, $c, $object, $params) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
local $dbh->{RaiseError} = 1;
return $self->txn_do(sub {
$object->{sort_id} = $self->create_insert_aisle({c => $c, parent => $object->{parent}, attr => $object->{parent_attr}, count => 1, after => $params->{after}});
my ($columns, $values) = $object->get_dirty_columns(); # DBIx::Class::Row yeah
my $insert_statement = qq{insert into "$type" (} . join (q{, }, map { qq{"$_"} } @sys_object_columns, @$columns) . ') values (' . join (q{, }, map { '?' } @sys_object_columns, @$columns) . ')';
if (my $retval = $dbh->do($insert_statement, undef, (map { $object->{$_} } @sys_object_columns), @$values)) {
$object->{id} = $dbh->last_insert_id(undef, undef, 'sys_object', undef, {sequence => 'sys_object_id_seq'});
return $retval;
}
});
}
=head2 update_object($c, $object)
Updates a CiderCMS::Object in the database.
=cut
sub update_object {
my ($self, $c, $object) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
my ($columns, $values) = $object->get_dirty_columns(); # DBIx::Class::Row yeah
my $update_statement = qq{update "$type" set } . join (q{, }, map { qq{"$_" = ?} } @sys_object_columns, @$columns) . ' where id = ?';
if (my $retval = $dbh->do($update_statement, undef, (map { $object->{$_} } @sys_object_columns), @$values, $object->{id})) {
return $retval;
}
else {
croak $dbh->errstr;
}
}
=head2 delete_object($c, $object)
Deletes a CiderCMS::Object from the database.
=cut
sub delete_object {
my ($self, $c, $object) = @_;
my $dbh = $self->dbh;
my $type = $object->{type};
if (my $retval = $dbh->do(qq{delete from "$type" where id = ?}, undef, $object->{id})) {
$self->close_aisle($c, $object->parent, $object->{parent_attr}, $object->{sort_id});
return $retval;
}
else {
croak $dbh->errstr;
}
}
=head2 move_object($c, $object, $params)
Moves a CiderCMS::Object to a new parent and or sort position
=cut
sub move_object {
my ($self, $c, $object, $params) = @_;
my ($old_parent, $old_parent_attr, $old_sort_id);
if ($params->{parent} and $params->{parent} != $object->{parent} or $params->{parent_attr} and $params->{parent_attr} ne $object->{parent_attr}) {
$old_parent = $object->parent;
$old_parent_attr = $object->{parent_attr};
$old_sort_id = $object->{sort_id};
$object->{parent} = $params->{parent}{id};
$object->{parent_attr} = $params->{parent_attr};
}
$object->{sort_id} = $self->create_insert_aisle({c => $c, parent => $object->{parent}, attr => $object->{parent_attr}, count => 1, after => $params->{after}});
my $result = $self->update_object($c, $object);
if ($old_parent) {
$self->close_aisle($c, $old_parent, $old_parent_attr, $old_sort_id);
}
return $result;
}
=head2 txn_do($code)
Run $sub in a transaction. Rollback transaction if $sub dies.
=cut
sub txn_do {
my ($self, $code) = @_;
my $dbh = $self->dbh;
my $in_txn = not $dbh->{AutoCommit};
$dbh->begin_work unless $in_txn;
my ($result, @results);
if (wantarray) {
@results = $code->();
}
else {
$result = $code->();
}
$dbh->commit unless $in_txn or $dbh->{AutoCommit};
return wantarray ? @results : $result;
}
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
DBI Model Class.
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Object.pm b/lib/CiderCMS/Object.pm
index 9db0fc9..5799797 100644
--- a/lib/CiderCMS/Object.pm
+++ b/lib/CiderCMS/Object.pm
@@ -13,576 +13,590 @@ use CiderCMS::Attribute;
=head1 NAME
CiderCMS::Object - Content objects
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
This class is the base for all content objects and provides the public API that can be used in templates.
=head1 METHODS
=head2 new({c => $c, id => 2, type => 'type1', parent => 1, parent_attr => 'children', sort_id => 0, data => {}})
=cut
sub new {
my ($class, $params) = @_;
$class = ref $class if ref $class;
my $c = $params->{c};
my $stash = $c->stash;
my $type = $params->{type};
my $data = $params->{data};
my $self = bless {
c => $params->{c},
id => $params->{id},
parent => $params->{parent},
parent_attr => $params->{parent_attr},
level => $params->{level},
type => $type,
sort_id => $params->{sort_id} || 0,
dcid => $params->{dcid},
attr => $stash->{types}{$type}{attr},
attributes => $stash->{types}{$type}{attributes},
}, $class;
weaken($self->{c});
foreach my $attr (@{ $self->{attributes} }) {
my $id = $attr->{id};
$self->{data}{$id} = $attr->{class}->new({c => $c, object => $self, data => $data->{$id}, %$attr});
}
return $self;
}
=head2 object_by_id($id)
Returns an object for the given ID
=cut
sub object_by_id {
my ($self, $id) = @_;
return $self->{c}->model('DB')->get_object($self->{c}, $id);
}
=head2 type
Returns the type info for this object.
For example:
{
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
=cut
sub type {
my ($self) = @_;
return $self->{c}->stash->{types}{$self->{type}};
}
=head2 property($property)
Returns the data of the named attribute
=cut
sub property {
my ($self, $property, $default) = @_;
unless (exists $self->{data}{$property}) {
return $default if @_ == 3;
croak "unknown property $property";
}
return $self->{data}{$property}->data;
}
=head2 set_property($property, $data)
Sets the named attribute to the given value
=cut
sub set_property {
my ($self, $property, $data) = @_;
return $self->{data}{$property}->set_data($data);
}
=head2 attribute($attribute)
Returns the CiderCMS::Attribute object for the named attribute
=cut
sub attribute {
my ($self, $attribute) = @_;
return unless exists $self->{data}{$attribute};
return $self->{data}{$attribute};
}
=head2 update_data($data)
Updates this object's data from a hashref.
=cut
sub update_data {
my ($self, $data) = @_;
foreach (values %{ $self->{data} }) {
$_->set_data_from_form($data);
}
return;
}
=head2 init_defaults()
Initialize this object's data to the attributes' default values.
=cut
sub init_defaults {
my ($self) = @_;
$_->init_default foreach values %{ $self->{data} };
return;
}
=head2 parent
Returns the parent of this object, if any.
=cut
sub parent {
my ($self) = @_;
return unless $self->{parent};
return $self->{c}->model('DB')->get_object($self->{c}, $self->{parent}, $self->{level} - 1);
}
=head2 parents
Returns the parent chain of this object including the object itself.
=cut
sub parents {
my ($self) = @_;
my $parent = $self;
my @parents = $parent;
unshift @parents, $parent while $parent = $parent->parent;
return \@parents;
}
=head2 parent_by_level($level)
Returns the parent at a certain level.
The site object is at level 0.
=cut
sub parent_by_level {
my ($self, $level) = @_;
return if $self->{level} < $level; # already on a lower level
my $parent = $self;
while ($parent) {
return $parent if $parent->{level} == $level;
$parent = $parent->parent;
}
return;
}
=head2 children()
Returns the children of this object regardless to which attribute they belong.
Usually one should use $object->property('my_attribute') to only get the children of a certain attribute.
Returns a list in list context and an array ref in scalar context.
=cut
sub children {
my ($self) = @_;
return $self->{c}->model('DB')->object_children($self->{c}, $self);
}
=head2 uri()
Returns an URI without a file name for this object
=cut
sub uri {
my ($self) = @_;
my $parent = $self->parent;
my $dcid = ($self->{dcid} // $self->{id});
return ( ($parent ? $parent->uri : $self->{c}->uri_for_instance()) . ($dcid ? "/$dcid" : '') );
}
=head2 uri_index()
Returns an URI to the first object in this subtree that contains page elements.
If none does, return the URI to the first child.
=cut
sub uri_index {
my ($self) = @_;
my @children = $self->children;
if (not @children or any { $_->type->{page_element} } @children) { # we contain no children at all or page elements
return $self->uri . '/index.html';
}
else {
return $children[0]->uri_index;
}
}
=head2 uri_management()
Returns an URI to the management interface for this object
=cut
sub uri_management {
my ($self) = @_;
return $self->uri . '/manage';
}
=head2 uri_static()
Returns an URI for static file for this object
=cut
sub uri_static {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->uri_static : $self->{c}->uri_static_for_instance()) . "/$self->{id}" );
}
=head2 fs_path()
Returns the file system path to this node
=cut
sub fs_path {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->fs_path : $self->{c}->fs_path_for_instance()) . "/$self->{id}" );
}
=head2 edit_form($errors)
Renders the form for editing this object.
The optional $errors may be a hash reference with error messages for attributes.
=cut
sub edit_form {
my ($self, $errors) = @_;
$errors //= {};
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => 'edit.zpt',
self => $self,
attributes => [
map {
$self->{data}{$_->{id}}->input_field($errors->{$_->{id}})
} @{ $self->{attributes} },
],
});
}
=head2 render()
Returns an HTML representation of this object.
=cut
sub render {
my ($self) = @_;
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => "types/$self->{type}.zpt",
self => $self,
});
}
=head2 validate($data)
Validate the given data.
Returns a hash containing messages for violated constraints:
{
attr1 => ['missing'],
attr2 => ['invalid', 'wrong'],
}
=cut
sub validate {
my ($self, $data) = @_;
my %results;
foreach (values %{ $self->{data} }) {
my @result = $_->validate($data);
$results{ $_->{id} } = \@result if @result;
}
return \%results if keys %results;
return;
}
=head2 prepare_attributes()
Prepares attributes for insert and update operations.
=cut
sub prepare_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->prepare_update();
}
return;
}
=head2 update_attributes()
Runs update operation on attributes after inserts and updates.
=cut
sub update_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->post_update();
}
return;
}
=head2 insert({after => $after})
Inserts the object into the database.
=cut
sub insert {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data(delete $params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->insert_object($self->{c}, $self, $params);
$self->update_attributes;
return $result;
}
=head2 update()
Updates the object in the database.
=cut
sub update {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data($params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->update_object($self->{c}, $self);
$self->update_attributes;
return $result;
}
=head2 delete_from_db()
Deletes the object and it's children.
=cut
sub delete_from_db {
my ($self) = @_;
foreach ($self->children) {
$_->delete_from_db;
}
return $self->{c}->model('DB')->delete_object($self->{c}, $self);
}
=head2 get_dirty_columns()
Returns two array refs with column names and corresponding values.
=cut
sub get_dirty_columns {
my ($self) = @_;
my (@columns, @values);
foreach (@{ $self->{attributes} }) {
my $id = $_->{id};
my $attr = $self->{data}{$id};
if ($attr->db_type) {
push @columns, $id;
push @values, $attr->{data}; #TODO introduce an $attr->raw_data
}
}
return \@columns, \@values;
}
=head2 move_to(parent => $parent, parent_attr => $parent_attr, after => $after)
Moves this object (and it's subtree) to a new parent and or sort position
=cut
sub move_to {
my ($self, %params) = @_;
my $old_fs_path = $self->fs_path;
my $result = $self->{c}->model('DB')->move_object($self->{c}, $self, \%params);
if (-e $old_fs_path) {
my $new_fs_path = $self->fs_path;
mkpath $self->parent->fs_path if $self->{parent};
move $old_fs_path, $new_fs_path;
}
return $result;
}
+=head2 refersh()
+
+Reloads this object from the database.
+
+=cut
+
+sub refresh {
+ my ($self) = @_;
+
+ my $fresh = $self->{c}->model('DB')->get_object($self->{c}, $self->{id});
+ %$self = %$fresh;
+ return $self;
+}
+
=head2 new_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in memory for the given attribute.
=cut
sub new_child {
my ($self, %params) = @_;
$params{c} = $self->{c};
$params{parent} = $self->{id};
$params{level} = $self->{level};
$params{parent_attr} = delete $params{attribute};
croak "Invalid attribute: $params{parent_attr}"
unless exists $self->{data}{ $params{parent_attr} };
return CiderCMS::Object->new(\%params);
}
=head2 create_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in the database for the given attribute.
=cut
sub create_child {
my ($self, %params) = @_;
# Don't give data to new_child. Instead give it to insert so it gets treated like
# data subitted through the management UI.
my $data = delete $params{data};
my $child = $self->new_child(%params);
$child->insert({data => $data});
return $child;
}
=head2 user_has_access
Returns whether the currently logged in user has access to this folder and all
parent folders.
=cut
sub user_has_access {
my ($self) = @_;
my $user = $self->{c}->user;
return 1 if $user;
return none { $_->property('restricted', 0) } @{ $self->parents };
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/t/paste.t b/t/paste.t
new file mode 100644
index 0000000..5bbfff6
--- /dev/null
+++ b/t/paste.t
@@ -0,0 +1,75 @@
+use strict;
+use warnings;
+use utf8;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+
+CiderCMS::Test->populate_types({
+ folder => {
+ name => 'Folder',
+ attributes => [
+ {
+ id => 'title',
+ data_type => 'Title',
+ mandatory => 1,
+ },
+ {
+ id => 'children',
+ data_type => 'Object',
+ mandatory => 0,
+ },
+ ],
+ },
+ textfield => {
+ name => 'Textfield',
+ attributes => [
+ {
+ id => 'text',
+ data_type => 'Text',
+ mandatory => 1,
+ },
+ ],
+ },
+});
+
+my $root = $model->get_object($c, 1);
+ my $source = $root->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Source' },
+ );
+ my @texts = reverse map {
+ $source->create_child(
+ attribute => 'children',
+ type => 'textfield',
+ data => {
+ text => "$_",
+ },
+ );
+ } reverse 1 .. 10;
+ my $destination = $root->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Destination' },
+ );
+
+$_->refresh foreach @texts;
+is_deeply [ map { $_->{sort_id} } @texts ], [ 1 .. @texts ];
+
+my $moving = shift @texts;
+$moving->move_to(parent => $destination, parent_attr => 'children');
+my @moved = $moving;
+
+$_->refresh foreach @texts;
+is_deeply [ map { $_->{sort_id} } @texts ], [ 1 .. @texts ];
+is($moving->refresh->{sort_id}, 1);
+
+($moving) = splice @texts, 1, 1;
+$moving->move_to(parent => $destination, parent_attr => 'children');
+push @moved, $moving;
+
+$_->refresh foreach @moved;
+is_deeply [ map { $_->{sort_id} } @moved ], [2, 1];
+
+done_testing;
|
niner/CiderCMS
|
108d0b7b90f6b5dc71bea6966865ad67cada2b6e
|
Fix CiderCMS::Test failing with current Catalyst
|
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index b355023..4921110 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,189 +1,205 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
+=head2 context
+
+Returns a $c object for tests.
+
+=cut
+
+sub context {
+ my ($self) = @_;
+
+ require Catalyst::Test;
+ Catalyst::Test->import('CiderCMS');
+ my ($res, $c) = ctx_request('/system/create');
+ delete $c->stash->{$_} foreach keys %{ $c->stash };
+
+ return $c;
+}
+
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
$ENV{ CIDERCMS_CONFIG_LOCAL_SUFFIX } = 'test';
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
- my $c = CiderCMS->new;
+ my $c = $self->context;
my $model = $c->model('DB');
- $c->req->_set_env({});
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
sub write_template {
my ($self, $file, $contents) = @_;
write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
}
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
undef $mech;
}
1;
|
niner/CiderCMS
|
1b3a7bc9f6b2a02ac415c4bddb7ae5a42bb2295d
|
Make thumbnail on non-existing images non-fatal
|
diff --git a/lib/CiderCMS/Attribute/Image.pm b/lib/CiderCMS/Attribute/Image.pm
index dbebfe2..3039fe6 100644
--- a/lib/CiderCMS/Attribute/Image.pm
+++ b/lib/CiderCMS/Attribute/Image.pm
@@ -1,67 +1,68 @@
package CiderCMS::Attribute::Image;
use strict;
use warnings;
use File::Path qw(mkpath rmtree);
use Image::Imlib2;
use base qw(CiderCMS::Attribute::File);
=head1 NAME
CiderCMS::Attribute::Image - Image attribute
=head1 SYNOPSIS
See L<CiderCMS::Attribute>
=head1 DESCRIPTION
Image attribute
=head1 METHODs
=head2 thumbnail($width, $height)
Returns the URL of a thumbnail conforming to the given size constraints.
=cut
sub thumbnail {
my ($self, $width, $height) = @_;
return unless $self->{data};
my $path = $self->fs_path;
my $thumb_name = $self->{data};
$thumb_name =~ s/(\. \w+) \z/_${width}_${height}$1/xm;
unless (-e "$path/$thumb_name") {
- my $image = Image::Imlib2->load("$path/$self->{data}");
+ my $image = eval { Image::Imlib2->load("$path/$self->{data}"); };
+ warn $@ if $@;
return '#nonexisting' unless $image;
if ($width and $height) {
(($image->width / $width > $image->height / $height) ? $height : $width) = 0;
}
my $thumb = $image->create_scaled_image($width, $height);
$thumb->set_quality(90);
$thumb->save("$path/$thumb_name");
}
return $self->{object}->uri_static . "/$self->{id}/$thumb_name";
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
|
niner/CiderCMS
|
4134c91f59bcb7d294a8970960fe3bbeb730047c
|
Fix error on pasting as new first child
|
diff --git a/root/static/js/scripts.js b/root/static/js/scripts.js
index 1788844..5b1467a 100644
--- a/root/static/js/scripts.js
+++ b/root/static/js/scripts.js
@@ -1,32 +1,35 @@
function cut(id) {
document.cookie = 'id=' + id + '; path=/'
return;
}
function paste(link, after) {
id = document.cookie.match(/\bid=\d+/);
- location.href = link.href + ';' + id + ';after=' + after;
+ var href = link.href + ';' + id;
+ if (after)
+ href += ';after=' + after;
+ location.href = href;
return false;
}
document.addEventListener("DOMContentLoaded", function() {
var edit_object_form = document.getElementById('edit_object_form');
if (edit_object_form) {
edit_object_form.onsubmit = function() {
var password = edit_object_form.querySelector('label.password input');
var repeat = edit_object_form.querySelector('label.password_repeat input');
if (password && repeat) {
var repeat_error = repeat.parentNode.querySelector('.repeat_error');
if (password.value == repeat.value) {
repeat_error.style.display = '';
return true;
}
else {
repeat_error.style.display = 'block';
alert(false);
return false;
}
}
}
}
}, false);
|
niner/CiderCMS
|
3ea3179b7bd0451674aa580dfcab4d71087b90a1
|
Implement inheritance of restrictions from parent folders
|
diff --git a/lib/CiderCMS/Object.pm b/lib/CiderCMS/Object.pm
index 5be5ac7..9db0fc9 100644
--- a/lib/CiderCMS/Object.pm
+++ b/lib/CiderCMS/Object.pm
@@ -1,570 +1,588 @@
package CiderCMS::Object;
use strict;
use warnings;
use Scalar::Util qw(weaken);
-use List::MoreUtils qw(any);
+use List::MoreUtils qw(any none);
use File::Path qw(mkpath);
use File::Copy qw(move);
use Carp qw(croak);
use CiderCMS::Attribute;
=head1 NAME
CiderCMS::Object - Content objects
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
This class is the base for all content objects and provides the public API that can be used in templates.
=head1 METHODS
=head2 new({c => $c, id => 2, type => 'type1', parent => 1, parent_attr => 'children', sort_id => 0, data => {}})
=cut
sub new {
my ($class, $params) = @_;
$class = ref $class if ref $class;
my $c = $params->{c};
my $stash = $c->stash;
my $type = $params->{type};
my $data = $params->{data};
my $self = bless {
c => $params->{c},
id => $params->{id},
parent => $params->{parent},
parent_attr => $params->{parent_attr},
level => $params->{level},
type => $type,
sort_id => $params->{sort_id} || 0,
dcid => $params->{dcid},
attr => $stash->{types}{$type}{attr},
attributes => $stash->{types}{$type}{attributes},
}, $class;
weaken($self->{c});
foreach my $attr (@{ $self->{attributes} }) {
my $id = $attr->{id};
$self->{data}{$id} = $attr->{class}->new({c => $c, object => $self, data => $data->{$id}, %$attr});
}
return $self;
}
=head2 object_by_id($id)
Returns an object for the given ID
=cut
sub object_by_id {
my ($self, $id) = @_;
return $self->{c}->model('DB')->get_object($self->{c}, $id);
}
=head2 type
Returns the type info for this object.
For example:
{
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
=cut
sub type {
my ($self) = @_;
return $self->{c}->stash->{types}{$self->{type}};
}
=head2 property($property)
Returns the data of the named attribute
=cut
sub property {
my ($self, $property, $default) = @_;
unless (exists $self->{data}{$property}) {
return $default if @_ == 3;
croak "unknown property $property";
}
return $self->{data}{$property}->data;
}
=head2 set_property($property, $data)
Sets the named attribute to the given value
=cut
sub set_property {
my ($self, $property, $data) = @_;
return $self->{data}{$property}->set_data($data);
}
=head2 attribute($attribute)
Returns the CiderCMS::Attribute object for the named attribute
=cut
sub attribute {
my ($self, $attribute) = @_;
return unless exists $self->{data}{$attribute};
return $self->{data}{$attribute};
}
=head2 update_data($data)
Updates this object's data from a hashref.
=cut
sub update_data {
my ($self, $data) = @_;
foreach (values %{ $self->{data} }) {
$_->set_data_from_form($data);
}
return;
}
=head2 init_defaults()
Initialize this object's data to the attributes' default values.
=cut
sub init_defaults {
my ($self) = @_;
$_->init_default foreach values %{ $self->{data} };
return;
}
=head2 parent
Returns the parent of this object, if any.
=cut
sub parent {
my ($self) = @_;
return unless $self->{parent};
return $self->{c}->model('DB')->get_object($self->{c}, $self->{parent}, $self->{level} - 1);
}
+=head2 parents
+
+Returns the parent chain of this object including the object itself.
+
+=cut
+
+sub parents {
+ my ($self) = @_;
+
+ my $parent = $self;
+ my @parents = $parent;
+ unshift @parents, $parent while $parent = $parent->parent;
+
+ return \@parents;
+}
+
=head2 parent_by_level($level)
Returns the parent at a certain level.
The site object is at level 0.
=cut
sub parent_by_level {
my ($self, $level) = @_;
return if $self->{level} < $level; # already on a lower level
my $parent = $self;
while ($parent) {
return $parent if $parent->{level} == $level;
$parent = $parent->parent;
}
return;
}
=head2 children()
Returns the children of this object regardless to which attribute they belong.
Usually one should use $object->property('my_attribute') to only get the children of a certain attribute.
Returns a list in list context and an array ref in scalar context.
=cut
sub children {
my ($self) = @_;
return $self->{c}->model('DB')->object_children($self->{c}, $self);
}
=head2 uri()
Returns an URI without a file name for this object
=cut
sub uri {
my ($self) = @_;
my $parent = $self->parent;
my $dcid = ($self->{dcid} // $self->{id});
return ( ($parent ? $parent->uri : $self->{c}->uri_for_instance()) . ($dcid ? "/$dcid" : '') );
}
=head2 uri_index()
Returns an URI to the first object in this subtree that contains page elements.
If none does, return the URI to the first child.
=cut
sub uri_index {
my ($self) = @_;
my @children = $self->children;
if (not @children or any { $_->type->{page_element} } @children) { # we contain no children at all or page elements
return $self->uri . '/index.html';
}
else {
return $children[0]->uri_index;
}
}
=head2 uri_management()
Returns an URI to the management interface for this object
=cut
sub uri_management {
my ($self) = @_;
return $self->uri . '/manage';
}
=head2 uri_static()
Returns an URI for static file for this object
=cut
sub uri_static {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->uri_static : $self->{c}->uri_static_for_instance()) . "/$self->{id}" );
}
=head2 fs_path()
Returns the file system path to this node
=cut
sub fs_path {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->fs_path : $self->{c}->fs_path_for_instance()) . "/$self->{id}" );
}
=head2 edit_form($errors)
Renders the form for editing this object.
The optional $errors may be a hash reference with error messages for attributes.
=cut
sub edit_form {
my ($self, $errors) = @_;
$errors //= {};
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => 'edit.zpt',
self => $self,
attributes => [
map {
$self->{data}{$_->{id}}->input_field($errors->{$_->{id}})
} @{ $self->{attributes} },
],
});
}
=head2 render()
Returns an HTML representation of this object.
=cut
sub render {
my ($self) = @_;
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => "types/$self->{type}.zpt",
self => $self,
});
}
=head2 validate($data)
Validate the given data.
Returns a hash containing messages for violated constraints:
{
attr1 => ['missing'],
attr2 => ['invalid', 'wrong'],
}
=cut
sub validate {
my ($self, $data) = @_;
my %results;
foreach (values %{ $self->{data} }) {
my @result = $_->validate($data);
$results{ $_->{id} } = \@result if @result;
}
return \%results if keys %results;
return;
}
=head2 prepare_attributes()
Prepares attributes for insert and update operations.
=cut
sub prepare_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->prepare_update();
}
return;
}
=head2 update_attributes()
Runs update operation on attributes after inserts and updates.
=cut
sub update_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->post_update();
}
return;
}
=head2 insert({after => $after})
Inserts the object into the database.
=cut
sub insert {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data(delete $params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->insert_object($self->{c}, $self, $params);
$self->update_attributes;
return $result;
}
=head2 update()
Updates the object in the database.
=cut
sub update {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data($params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->update_object($self->{c}, $self);
$self->update_attributes;
return $result;
}
=head2 delete_from_db()
Deletes the object and it's children.
=cut
sub delete_from_db {
my ($self) = @_;
foreach ($self->children) {
$_->delete_from_db;
}
return $self->{c}->model('DB')->delete_object($self->{c}, $self);
}
=head2 get_dirty_columns()
Returns two array refs with column names and corresponding values.
=cut
sub get_dirty_columns {
my ($self) = @_;
my (@columns, @values);
foreach (@{ $self->{attributes} }) {
my $id = $_->{id};
my $attr = $self->{data}{$id};
if ($attr->db_type) {
push @columns, $id;
push @values, $attr->{data}; #TODO introduce an $attr->raw_data
}
}
return \@columns, \@values;
}
=head2 move_to(parent => $parent, parent_attr => $parent_attr, after => $after)
Moves this object (and it's subtree) to a new parent and or sort position
=cut
sub move_to {
my ($self, %params) = @_;
my $old_fs_path = $self->fs_path;
my $result = $self->{c}->model('DB')->move_object($self->{c}, $self, \%params);
if (-e $old_fs_path) {
my $new_fs_path = $self->fs_path;
mkpath $self->parent->fs_path if $self->{parent};
move $old_fs_path, $new_fs_path;
}
return $result;
}
=head2 new_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in memory for the given attribute.
=cut
sub new_child {
my ($self, %params) = @_;
$params{c} = $self->{c};
$params{parent} = $self->{id};
$params{level} = $self->{level};
$params{parent_attr} = delete $params{attribute};
croak "Invalid attribute: $params{parent_attr}"
unless exists $self->{data}{ $params{parent_attr} };
return CiderCMS::Object->new(\%params);
}
=head2 create_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in the database for the given attribute.
=cut
sub create_child {
my ($self, %params) = @_;
# Don't give data to new_child. Instead give it to insert so it gets treated like
# data subitted through the management UI.
my $data = delete $params{data};
my $child = $self->new_child(%params);
$child->insert({data => $data});
return $child;
}
=head2 user_has_access
Returns whether the currently logged in user has access to this folder and all
parent folders.
=cut
sub user_has_access {
my ($self) = @_;
- return (not $self->property('restricted', 0) or $self->{c}->user);
+ my $user = $self->{c}->user;
+ return 1 if $user;
+ return none { $_->property('restricted', 0) } @{ $self->parents };
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/t/authentication.t b/t/authentication.t
index 5fa7794..0f02d40 100644
--- a/t/authentication.t
+++ b/t/authentication.t
@@ -1,169 +1,185 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
use FindBin qw($Bin);
$model->create_type($c, {id => 'folder', name => 'Folder', page_element => 0});
$model->create_attribute($c, {
type => 'folder',
id => 'title',
name => 'Title',
sort_id => 0,
data_type => 'Title',
repetitive => 0,
mandatory => 1,
default_value => '',
});
$model->create_attribute($c, {
type => 'folder',
id => 'restricted',
name => 'Restricted',
sort_id => 1,
data_type => 'Boolean',
repetitive => 0,
mandatory => 0,
default_value => 0,
});
$model->create_attribute($c, {
type => 'folder',
id => 'children',
name => 'Children',
sort_id => 1,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => 0,
});
$model->create_type($c, {id => 'user', name => 'User', page_element => 1});
$model->create_attribute($c, {
type => 'user',
id => 'username',
name => 'Name',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
});
$model->create_attribute($c, {
type => 'user',
id => 'password',
name => 'Password',
sort_id => 1,
data_type => 'Password',
repetitive => 0,
mandatory => 1,
default_value => '',
});
open my $template, '>', "$Bin/../root/instances/$instance/templates/types/user.zpt";
print $template q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>);
close $template;
$mech->get_ok("http://localhost/$instance/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Users',
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Unrestricted',
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a restricted folder');
$mech->submit_form_ok({
with_fields => {
title => 'Restricted',
restricted => '1',
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/unrestricted/index.html");
$mech->content_lacks('Login');
# Try accessing restricted content
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
# Try logging in with a non-existing user
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->content_contains('Invalid username/password');
$mech->get_ok("http://localhost/$instance/users/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=user} }, 'Add a user');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
button => 'save',
});
ok($mech->find_xpath('//div[text()="test"]'), 'new user listed');
# Try logging in with the wrong password
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'wrong',
},
});
$mech->content_contains('Invalid username/password');
# Now that the user exists, try to login again with correct credentials
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->content_lacks('Invalid username/password');
ok($mech->find_xpath('id("object_4")'), 'Login successful');
$mech->get_ok("http://localhost/$instance/users/manage");
$mech->follow_link_ok({text => 'User'});
$mech->submit_form_ok({
with_fields => {
password => 'test2',
},
button => 'save',
});
$mech->get_ok("http://localhost/system/logout");
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test2',
},
});
$mech->content_lacks('Invalid username/password');
ok($mech->find_xpath('id("object_4")'), 'Login successful');
+# Test subfolder of restricted folder
+$mech->get_ok("http://localhost/$instance/restricted/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a sub folder to restricted folder');
+$mech->submit_form_ok({
+ with_fields => {
+ title => 'Subfolder',
+ },
+ button => 'save',
+});
+$mech->get_ok("http://localhost/$instance/restricted/subfolder/index.html");
+$mech->content_lacks('Login');
+
+$mech->get_ok("http://localhost/system/logout");
+$mech->get_ok("http://localhost/$instance/restricted/subfolder/index.html");
+$mech->content_contains('Login');
+
done_testing;
|
niner/CiderCMS
|
e1f4e3446a43cc0d3d068a0875dadcd43d5e270b
|
Fix registration failing with PostgreSQL 9.3
|
diff --git a/root/initial_schema.sql b/root/initial_schema.sql
index 506ad20..3b38466 100644
--- a/root/initial_schema.sql
+++ b/root/initial_schema.sql
@@ -1,103 +1,103 @@
SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;
SET default_with_oids = false;
CREATE TABLE sys_types (
id character varying NOT NULL primary key,
name character varying NOT NULL,
page_element boolean NOT NULL default false
);
CREATE TABLE sys_attributes (
type character varying NOT NULL references sys_types (id) deferrable,
id character varying NOT NULL,
name character varying NOT NULL,
sort_id integer DEFAULT 0 NOT NULL,
data_type character varying NOT NULL,
repetitive boolean DEFAULT false NOT NULL,
mandatory boolean DEFAULT false NOT NULL,
default_value character varying,
primary key (type, id)
);
CREATE TABLE sys_object (
id integer NOT NULL primary key,
parent integer,
parent_attr varchar,
sort_id integer DEFAULT 0 NOT NULL,
type character varying NOT NULL references sys_types (id),
changed timestamp not null default now(),
tree_changed timestamp not null default now(),
active_start timestamp without time zone,
active_end timestamp without time zone,
dcid character varying,
constraint unique_dcid unique (parent, dcid),
constraint unique_sort_id unique (parent, parent_attr, sort_id)
);
CREATE SEQUENCE sys_object_id_seq
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO MINVALUE
CACHE 1;
ALTER SEQUENCE sys_object_id_seq OWNED BY sys_object.id;
ALTER TABLE sys_object ALTER COLUMN id SET DEFAULT nextval('sys_object_id_seq'::regclass);
CREATE OR REPLACE FUNCTION sys_objects_bi() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
IF NEW.id IS NOT NULL THEN
insert into sys_object (id, parent, parent_attr, sort_id, type, changed, tree_changed, active_start, active_end, dcid) values (NEW.id, NEW.parent, NEW.parent_attr, NEW.sort_id, TG_TABLE_NAME, NEW.changed, NEW.tree_changed, NEW.active_start, NEW.active_end, NEW.dcid) returning id into NEW.id;
ELSE
insert into sys_object (parent, parent_attr, sort_id, type, changed, tree_changed, active_start, active_end, dcid) values (NEW.parent, NEW.parent_attr, NEW.sort_id, TG_TABLE_NAME, NEW.changed, NEW.tree_changed, NEW.active_start, NEW.active_end, NEW.dcid) returning id into NEW.id;
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION sys_objects_bu() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
IF NEW.id <> OLD.id THEN
RAISE EXCEPTION 'Changing ids is forbidden.';
END IF;
update sys_object set id=NEW.id, parent=NEW.parent, parent_attr=NEW.parent_attr, sort_id=NEW.sort_id, changed=NEW.changed, tree_changed=NEW.tree_changed, active_start=NEW.active_start, active_end=NEW.active_end, dcid=NEW.dcid where id=NEW.id;
RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION sys_objects_ad() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
delete from sys_object where id = OLD.id;
RETURN OLD;
END;
$BODY$
LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION sys_object_au() RETURNS TRIGGER AS
$BODY$
DECLARE
BEGIN
- IF OLD.sort_id IS DISTINCT FROM NEW.sort_id OR OLD.parent IS DISTINCT FROM NEW.parent OR OLD.parent_attr IS DISTINCT FROM NEW.parent_attr THEN
+ IF pg_trigger_depth() < 2 AND (OLD.sort_id IS DISTINCT FROM NEW.sort_id OR OLD.parent IS DISTINCT FROM NEW.parent OR OLD.parent_attr IS DISTINCT FROM NEW.parent_attr) THEN
EXECUTE 'update ' || quote_ident(NEW.type) || ' set sort_id=' || NEW.sort_id || ', parent=' || NEW.parent || ', parent_attr=''' || NEW.parent_attr || ''' where id=' || NEW.id;
END IF;
RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql';
create trigger sys_object_au after update on sys_object for each row execute procedure sys_object_au();
|
niner/CiderCMS
|
2475d24b128d3cf357c35cba2d728be408c5900c
|
Unicode::Encoding no longer needed on Catalyst 5.90070
|
diff --git a/Makefile.PL b/Makefile.PL
index dea47e8..cd4f817 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,46 +1,46 @@
#!/usr/bin/env perl
# IMPORTANT: if you delete this file your app will not work as
# expected. You have been warned.
use inc::Module::Install;
name 'CiderCMS';
all_from 'lib/CiderCMS.pm';
-requires 'Catalyst::Runtime' => '5.80011';
+requires 'Catalyst::Runtime' => '5.90070';
requires 'Catalyst::Plugin::ConfigLoader';
requires 'Catalyst::Plugin::Static::Simple';
requires 'Catalyst::Plugin::Unicode::Encoding';
requires 'Catalyst::Plugin::Session';
requires 'Catalyst::Plugin::Session::State::Cookie';
requires 'Catalyst::Plugin::Session::Store::FastMmap';
requires 'Catalyst::Action::RenderView';
requires 'parent';
requires 'Config::General'; # This should reflect the config file format you've chosen
# See Catalyst::Plugin::ConfigLoader for supported formats
requires 'Catalyst::Model::DBI';
requires 'Catalyst::View::Petal';
requires 'Petal::Utils';
requires 'Catalyst::Plugin::FormValidator';
requires 'DateTime';
requires 'DateTime::Format::ISO8601';
requires 'DateTime::Format::Flexible';
requires 'DateTime::Span';
requires 'Digest::SHA';
requires 'Module::Pluggable';
requires 'Image::Imlib2';
requires 'File::Path';
requires 'File::Copy';
requires 'File::Temp';
requires 'File::Find';
requires 'File::Slurp';
requires 'Cwd';
requires 'MIME::Lite';
requires 'Email::Sender::Simple';
requires 'Email::Stuffer';
requires 'Regexp::Common::URI';
catalyst_ignore('root'); # avoid copying root/static/instances
catalyst;
install_script glob('script/*.pl');
auto_install;
WriteAll;
diff --git a/lib/CiderCMS.pm b/lib/CiderCMS.pm
index 4bb1659..dd7788c 100644
--- a/lib/CiderCMS.pm
+++ b/lib/CiderCMS.pm
@@ -1,188 +1,187 @@
package CiderCMS;
use strict;
use warnings;
use Catalyst::Runtime 5.80;
use Catalyst::DispatchType::CiderCMS;
# Set flags and add plugins for the application
#
# ConfigLoader: will load the configuration from a Config::General file in the
# application's home directory
# Static::Simple: will serve static files from the application's root
# directory
use parent qw/Catalyst/;
use Catalyst qw/
- Unicode::Encoding
ConfigLoader
Static::Simple
FormValidator
Authentication
Session
Session::State::Cookie
Session::Store::FastMmap
/;
our $VERSION = '0.01';
# Configure the application.
#
# Note that settings in cidercms.conf (or other external
# configuration file that you set up manually) take precedence
# over this when using ConfigLoader. Thus configuration
# details given here can function as a default configuration,
# with an external configuration file acting as an override for
# local deployment.
__PACKAGE__->config(
name => 'CiderCMS',
encoding => 'UTF-8',
);
# Start the application
__PACKAGE__->setup();
=head1 NAME
CiderCMS - Catalyst based application
=head1 SYNOPSIS
script/cidercms_server.pl
=head1 DESCRIPTION
CiderCMS is a very flexible CMS.
=head1 METHODS
=head2 prepare_path
Checks for an CIDERCMS_INSTANCE environment variable and prepends it to the path if present.
=cut
sub prepare_path {
my ($self, @args) = @_;
$self->maybe::next::method(@args);
my $uri_raw = $self->request->uri->clone;
if (my $instance = $ENV{CIDERCMS_INSTANCE}) {
my $uri = $uri_raw->clone;
my $path = $instance . $uri->path;
$uri->path($path);
$self->request->path($path);
$uri->path_query('');
$uri->fragment(undef);
$self->stash({
uri_instance => $uri,
uri_static => "$uri/static",
uri_raw => $uri_raw,
});
}
else {
$self->stash->{uri_raw} = $uri_raw;
}
return;
}
if ($ENV{CIDERCMS_INSTANCE}) {
__PACKAGE__->config->{static}{include_path} = [
__PACKAGE__->config->{root} . '/instances/',
__PACKAGE__->config->{root},
];
}
=head2 uri_for_instance(@path)
Creates an URI relative to the current instance's root
=cut
sub uri_for_instance {
my ($self, @path) = @_;
return ($self->stash->{uri_instance} ||= $self->uri_for('/') . $self->stash->{instance}) . (@path ? join '/', '', @path : '');
}
=head2 uri_static_for_instance()
Returns an URI for static files for this instance
=cut
sub uri_static_for_instance {
my ($self, @path) = @_;
return join '/', ($self->stash->{uri_static} or $self->uri_for('/') . (join '/', 'instances', $self->stash->{instance}, 'static')), @path;
}
=head2 fs_path_for_instance()
Returns a file system path for the current instance's root
=cut
sub fs_path_for_instance {
my ($self) = @_;
return $self->config->{root} . '/instances/' . $self->stash->{instance} . '/static';
}
=head2 register_management_action
Controllers may register subroutines returning additional actions for the management interface dynamically.
For example:
CiderCMS->register_management_action(__PACKAGE__, sub {
my ($self, $c) = @_;
return {title => 'Foo', uri => $c->uri_for('foo')}, { ... };
});
=cut
my %management_actions;
sub register_management_action {
my ($self, $package, $action_creator) = @_;
$management_actions{$package} = $action_creator;
return;
}
=head2 management_actions
Returns the registered management actions
=cut
sub management_actions {
my ($self) = @_;
return \%management_actions;
}
=head1 SEE ALSO
L<CiderCMS::Controller::Root>, L<Catalyst>
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
|
niner/CiderCMS
|
0075252fd9780975310f910fd337ab013fca1bdc
|
Fix "Can't call method "delete" on an undefined value during global destruction" in tests
|
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index 18bdb13..b355023 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,188 +1,189 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
$ENV{ CIDERCMS_CONFIG_LOCAL_SUFFIX } = 'test';
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
my $c = CiderCMS->new;
my $model = $c->model('DB');
$c->req->_set_env({});
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
sub write_template {
my ($self, $file, $contents) = @_;
write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
}
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
+ undef $mech;
}
1;
|
niner/CiderCMS
|
303552867c269d530d9e5c0986cc9ff9868442ec
|
Fix test failing with Catalyst 5.90070
|
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index 0ac75d3..18bdb13 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,187 +1,188 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
$ENV{ CIDERCMS_CONFIG_LOCAL_SUFFIX } = 'test';
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
my $c = CiderCMS->new;
my $model = $c->model('DB');
+ $c->req->_set_env({});
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
sub write_template {
my ($self, $file, $contents) = @_;
write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
}
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
}
1;
|
niner/CiderCMS
|
a2d74fefeb5d0d252553b3b559b4019a97d153c8
|
Allow new DateTime flexibility for reservation as well
|
diff --git a/lib/CiderCMS/Attribute/DateTime.pm b/lib/CiderCMS/Attribute/DateTime.pm
index 14debb2..a21790e 100644
--- a/lib/CiderCMS/Attribute/DateTime.pm
+++ b/lib/CiderCMS/Attribute/DateTime.pm
@@ -1,170 +1,171 @@
package CiderCMS::Attribute::DateTime;
use strict;
use warnings;
use v5.14;
use DateTime;
use DateTime::Format::Flexible;
+use DateTime::Format::ISO8601;
use base qw(CiderCMS::Attribute::Date CiderCMS::Attribute::Time);
=head1 NAME
CiderCMS::Attribute::DateTime - DateTime attribute
=head1 SYNOPSIS
See L<CiderCMS::Attribute>
=head1 DESCRIPTION
Composed date and time attribute
=head1 METHODs
=head2 db_type
=cut
sub db_type {
return 'timestamp';
}
=head2 set_data_from_form($data)
Sets this attribute's data from submitted form data.
=cut
sub set_data_from_form {
my ($self, $data) = @_;
my $value = $data->{ $self->id . '_date' } . ' ' . $data->{ $self->id . '_time' };
- $value = parse_datetime($value);
+ $value = $self->parse_datetime($value);
return $self->set_data($value->iso8601);
}
=head2 validate
=cut
sub validate {
my ($self, $data) = @_;
my $date = $data->{ $self->id . '_date' };
my $time = $data->{ $self->id . '_time' };
my $value = $date ? $time ? "$date $time" : $date : undef;
return 'missing' if $self->{mandatory} and not defined $value;
my $parsed = eval {
- parse_datetime($value);
+ $self->parse_datetime($value);
};
return 'invalid' if $@;
return;
}
sub parse_datetime {
- my ($value) = @_;
+ my ($self, $value) = @_;
$value .= ':0' unless $value =~ /\d+:\d+:\d+/;
- DateTime::Format::Flexible->parse_datetime($value, european => 1);
+ return DateTime::Format::Flexible->parse_datetime($value, european => 1);
}
=head2 object
Returns a L<DateTime> object initialized with this attribute's data
=cut
sub object {
my ($self) = @_;
return DateTime::Format::ISO8601->parse_datetime($self->data =~ s/ /T/r);
}
=head2 filter_matches($value)
Returns true if this attribute matches the given filter value.
$value may be 'future' to check if this date lies in the future.
=cut
sub filter_matches {
my ($self, $value) = @_;
if ($value eq 'past') {
return DateTime->now > $self->object;
}
if ($value eq 'future') {
return DateTime->now < $self->object;
}
if ($value eq 'today') {
return DateTime->now->ymd eq $self->object->ymd;
}
return;
}
=head2 is_today()
Returns true if the stored day is today.
=cut
sub is_today {
my ($self, $value) = @_;
return DateTime->now->ymd eq $self->object->ymd;
}
=head2 format($format)
Returns a representation of the stored time according to the given format.
See 'strftime Patterns' in L<DateTime> for details about the format.
=cut
sub format {
my ($self, $format) = @_;
return $self->object->strftime($format);
}
=head2 delegated methods
See L<DateTime> for a description of these methods.
=head3 ymd
=cut
sub ymd {
my ($self) = @_;
return $self->object->ymd;
}
=head3 time
=cut
sub time {
my ($self) = @_;
return $self->object->time;
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Controller/Custom/Reservation.pm b/lib/CiderCMS/Controller/Custom/Reservation.pm
index c3f9949..db023f1 100644
--- a/lib/CiderCMS/Controller/Custom/Reservation.pm
+++ b/lib/CiderCMS/Controller/Custom/Reservation.pm
@@ -1,155 +1,152 @@
package CiderCMS::Controller::Custom::Reservation;
use strict;
use warnings;
use parent 'Catalyst::Controller';
-use DateTime::Format::ISO8601;
use DateTime::Span;
use Hash::Merge qw(merge);
=head2 reserve
Reserve the displayed plane.
=cut
sub reserve : CiderCMS('reserve') {
my ( $self, $c ) = @_;
$c->detach('/user/login') unless $c->user;
my $params = $c->req->params;
my $save = delete $params->{save};
my $object = $c->stash->{context}->new_child(
attribute => 'reservations',
type => 'reservation',
);
my $errors = {};
if ($save) {
$errors = $object->validate($params);
unless ($errors) {
$params->{start_time} = sprintf '%02i:%02i', split /:/, $params->{start_time};
- my $start = DateTime::Format::ISO8601->new(
- base_datetime => DateTime->now(time_zone => 'floating'),
- )->parse_datetime(
- "$params->{start_date}T$params->{start_time}"
+ my $start = CiderCMS::Attribute::DateTime->parse_datetime(
+ "$params->{start_date} $params->{start_time}"
);
$errors = merge(
$self->check_time_limit($c, $start),
$self->check_conflicts($c, $start, $params->{end}),
);
}
unless ($errors) {
$object->insert({data => $params});
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
$_ = join ', ', @$_ foreach values %$errors;
}
else {
$object->init_defaults;
}
$c->stash->{reservation} = 1;
$c->stash->{reserve} = 1;
my $content = $c->view('Petal')->render_template(
$c,
{
user => $c->user->get('name'),
%{ $c->stash },
%$params,
template => 'custom/reservation/reserve.zpt',
uri_cancel => $c->stash->{context}->uri . '/cancel',
errors => $errors,
},
);
$c->stash({
template => 'index.zpt',
content => $content,
});
return;
}
=head3 check_time_limit($c, $start)
=cut
sub check_time_limit {
my ($self, $c, $start) = @_;
my $time_limit = $c->stash->{context}->property('reservation_time_limit', undef);
return unless $time_limit;
my $limit = DateTime->now(time_zone => 'local')
->set_time_zone('floating')
->add(hours => $time_limit);
return {start => ['too close']} if $start->datetime lt $limit->datetime;
return;
}
=head3 check_conflicts($c, $start)
=cut
sub check_conflicts {
my ($self, $c, $start, $end) = @_;
my $reservations = $c->stash->{context}->attribute('reservations');
my $new = create_datetime_span($start, $end);
foreach my $existing (@{ $reservations->filtered(cancelled_by => undef) }) {
my $existing = create_datetime_span(
$existing->attribute('start')->object,
$existing->property('end')
);
if ($new->intersects($existing)) {
return {start => ['conflicting existent reservation']};
}
}
return;
}
=head4 create_datetime_span($start, $end)
=cut
sub create_datetime_span {
my ($start, $end) = @_;
my ($end_h, $end_m) = split /:/, $end;
return DateTime::Span->from_datetimes(
start => $start,
end => $start->clone->set_hour($end_h)->set_minute($end_m)->subtract(seconds => 1)
);
}
=head2 cancel
Cancel the given reservation.
=cut
sub cancel : CiderCMS('cancel') Args(1) {
my ($self, $c, $id) = @_;
$c->detach('/user/login') unless $c->user;
my $context = $c->stash->{context};
my $reservation = $c->model('DB')->get_object($c, $id, $context->{level} + 1);
if ($reservation->{parent} == $context->{id}) {
$reservation->set_property(cancelled_by => $c->user->get('name'));
$reservation->update;
}
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
1;
diff --git a/t/custom_reservation.t b/t/custom_reservation.t
index cb49c22..92f1784 100644
--- a/t/custom_reservation.t
+++ b/t/custom_reservation.t
@@ -1,290 +1,303 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
repetitive => 1,
},
],
},
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'name',
data_type => 'String',
},
],
},
reservation => {
name => 'Reservation',
page_element => 1,
attributes => [
{
id => 'start',
data_type => 'DateTime',
mandatory => 1,
},
{
id => 'end',
data_type => 'Time',
mandatory => 1,
},
{
id => 'user',
data_type => 'String',
},
{
id => 'info',
data_type => 'String',
},
{
id => 'cancelled_by',
data_type => 'String',
},
],
},
airplane => {
name => 'Airplane',
page_element => 1,
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'reservations',
data_type => 'Object',
repetitive => 1,
},
{
id => 'reservation_time_limit',
data_type => 'Integer',
},
],
template => 'airplane.zpt'
},
});
my $root = $model->get_object($c, 1);
my $users = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Users' },
);
$users->create_child(
attribute => 'children',
type => 'user',
data => {
username => 'test',
name => 'test',
password => 'test',
},
);
my $airplanes = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Airplanes' },
);
my $dimona = $airplanes->create_child(
attribute => 'children',
type => 'airplane',
data => {
title => 'Dimona',
},
);
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->content_contains('Keine Reservierungen eingetragen.');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
$mech->content_lacks('Keine Reservierungen eingetragen.');
ok($mech->find_xpath(qq{//td[span="Heute"]}), "Today's reservation listed");
ok($mech->find_xpath(qq{//td[text()="test"]}), 'reserving user listed');
ok($mech->find_xpath(qq{//td[text()="Testflug"]}), 'Info listed');
$date->add(days => 1);
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
ok($mech->find_xpath(q{//td[span="Heute"]}), "Today's reservation still listed");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
$mech->get_ok(
$mech->find_xpath(q{//tr[td="Heute"]/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
is('' . $mech->find_xpath(q{//td[text()="Heute"]}), '', "Today's reservation gone");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/6/manage");
is($mech->value('cancelled_by'), 'test');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "conflicting existent reservation"]'),
'error message for conflict with existent reservation found'
);
$mech->get_ok("http://localhost/system/logout");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->get_ok(
$mech->find_xpath(q{//tr/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
not($mech->find_xpath('//span[text() = "conflicting existent reservation"]')),
'error message for conflict with existent reservation not found anymore'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
# test error handling
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => 'invalid',
start_time => 'nonsense',
end => 'forget',
info => '',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
+ $mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
+ my $year = DateTime->now->add(years => 1)->year;
+ $mech->submit_form_ok({
+ with_fields => {
+ start_date => "6.12.$year",
+ start_time => '10:00',
+ end => '13:00',
+ info => '',
+ },
+ button => 'save',
+ });
+ ok(not($mech->find_xpath('//span[text() = "invalid"]')), 'valid date -> no error message');
+
$model->dbh->rollback;
});
$model->txn_do(sub {
# Update to test advance time limit
$dimona->set_property(reservation_time_limit => 24);
$dimona->update;
my $now = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->clone->add(hours => 1)->hms,
end => $now->clone->add(hours => 2)->hms,
info => 'too close',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "too close"]'), 'error message for too close date found');
$now = DateTime->now->add(days => 2)->add(hours => 4);
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->hms,
end => $now->clone->add(hours => 1)->hms,
info => 'too close',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too close"]'),
'',
'error message for too close date gone'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
ok($mech->find_xpath(qq{//p[text()="Frei"]}), "No reservation active for now");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->subtract(hours => 1)->hms(':'),
end => $date->clone->add(hours => 2)->hour . ':00',
info => 'Testflug',
},
button => 'save',
});
is('' . $mech->find_xpath(qq{//p[text()="Frei"]}), '', "Reservation active for now");
$model->dbh->rollback;
});
done_testing;
|
niner/CiderCMS
|
21177f6a57228095a1c477b14ff80675e40f939c
|
Be far more flexible when reading DateTime input
|
diff --git a/Makefile.PL b/Makefile.PL
index c0d5cb8..dea47e8 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,45 +1,46 @@
#!/usr/bin/env perl
# IMPORTANT: if you delete this file your app will not work as
# expected. You have been warned.
use inc::Module::Install;
name 'CiderCMS';
all_from 'lib/CiderCMS.pm';
requires 'Catalyst::Runtime' => '5.80011';
requires 'Catalyst::Plugin::ConfigLoader';
requires 'Catalyst::Plugin::Static::Simple';
requires 'Catalyst::Plugin::Unicode::Encoding';
requires 'Catalyst::Plugin::Session';
requires 'Catalyst::Plugin::Session::State::Cookie';
requires 'Catalyst::Plugin::Session::Store::FastMmap';
requires 'Catalyst::Action::RenderView';
requires 'parent';
requires 'Config::General'; # This should reflect the config file format you've chosen
# See Catalyst::Plugin::ConfigLoader for supported formats
requires 'Catalyst::Model::DBI';
requires 'Catalyst::View::Petal';
requires 'Petal::Utils';
requires 'Catalyst::Plugin::FormValidator';
requires 'DateTime';
requires 'DateTime::Format::ISO8601';
+requires 'DateTime::Format::Flexible';
requires 'DateTime::Span';
requires 'Digest::SHA';
requires 'Module::Pluggable';
requires 'Image::Imlib2';
requires 'File::Path';
requires 'File::Copy';
requires 'File::Temp';
requires 'File::Find';
requires 'File::Slurp';
requires 'Cwd';
requires 'MIME::Lite';
requires 'Email::Sender::Simple';
requires 'Email::Stuffer';
requires 'Regexp::Common::URI';
catalyst_ignore('root'); # avoid copying root/static/instances
catalyst;
install_script glob('script/*.pl');
auto_install;
WriteAll;
diff --git a/lib/CiderCMS/Attribute/DateTime.pm b/lib/CiderCMS/Attribute/DateTime.pm
index 95f4c7a..14debb2 100644
--- a/lib/CiderCMS/Attribute/DateTime.pm
+++ b/lib/CiderCMS/Attribute/DateTime.pm
@@ -1,169 +1,170 @@
package CiderCMS::Attribute::DateTime;
use strict;
use warnings;
use v5.14;
use DateTime;
+use DateTime::Format::Flexible;
use base qw(CiderCMS::Attribute::Date CiderCMS::Attribute::Time);
=head1 NAME
CiderCMS::Attribute::DateTime - DateTime attribute
=head1 SYNOPSIS
See L<CiderCMS::Attribute>
=head1 DESCRIPTION
Composed date and time attribute
=head1 METHODs
=head2 db_type
=cut
sub db_type {
return 'timestamp';
}
=head2 set_data_from_form($data)
Sets this attribute's data from submitted form data.
=cut
sub set_data_from_form {
my ($self, $data) = @_;
my $value = $data->{ $self->id . '_date' } . ' ' . $data->{ $self->id . '_time' };
+ $value = parse_datetime($value);
- return $self->set_data($value);
+ return $self->set_data($value->iso8601);
}
=head2 validate
=cut
sub validate {
my ($self, $data) = @_;
my $date = $data->{ $self->id . '_date' };
my $time = $data->{ $self->id . '_time' };
my $value = $date ? $time ? "$date $time" : $date : undef;
+ return 'missing' if $self->{mandatory} and not defined $value;
- return
- ( ($self->{mandatory} and not defined $value) ? 'missing' : ()),
- (
- $value
- and $value !~ /
- \A
- \d{4}-\d{2}-\d{2}
- (?: T | \s )
- (?: [01]?\d | 2[0-3]) : [0-5][0-9] (?: : [0-5][0-9])?
- \z
- /xm
- )
- ? 'invalid'
- : ();
+ my $parsed = eval {
+ parse_datetime($value);
+ };
+ return 'invalid' if $@;
+ return;
+}
+
+sub parse_datetime {
+ my ($value) = @_;
+
+ $value .= ':0' unless $value =~ /\d+:\d+:\d+/;
+ DateTime::Format::Flexible->parse_datetime($value, european => 1);
}
=head2 object
Returns a L<DateTime> object initialized with this attribute's data
=cut
sub object {
my ($self) = @_;
return DateTime::Format::ISO8601->parse_datetime($self->data =~ s/ /T/r);
}
=head2 filter_matches($value)
Returns true if this attribute matches the given filter value.
$value may be 'future' to check if this date lies in the future.
=cut
sub filter_matches {
my ($self, $value) = @_;
if ($value eq 'past') {
return DateTime->now > $self->object;
}
if ($value eq 'future') {
return DateTime->now < $self->object;
}
if ($value eq 'today') {
return DateTime->now->ymd eq $self->object->ymd;
}
return;
}
=head2 is_today()
Returns true if the stored day is today.
=cut
sub is_today {
my ($self, $value) = @_;
return DateTime->now->ymd eq $self->object->ymd;
}
=head2 format($format)
Returns a representation of the stored time according to the given format.
See 'strftime Patterns' in L<DateTime> for details about the format.
=cut
sub format {
my ($self, $format) = @_;
return $self->object->strftime($format);
}
=head2 delegated methods
See L<DateTime> for a description of these methods.
=head3 ymd
=cut
sub ymd {
my ($self) = @_;
return $self->object->ymd;
}
=head3 time
=cut
sub time {
my ($self) = @_;
return $self->object->time;
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/t/Attribute-DateTime.t b/t/Attribute-DateTime.t
index ec3cb0b..961b22b 100644
--- a/t/Attribute-DateTime.t
+++ b/t/Attribute-DateTime.t
@@ -1,101 +1,129 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
CiderCMS::Test->populate_types({
tester => {
name => 'Tester',
attributes => [
{
id => 'test',
data_type => 'DateTime',
mandatory => 1,
},
],
template => 'datetime_test.zpt',
},
});
$mech->get_ok("http://localhost/$instance/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=tester} }, 'Add a tester');
$mech->submit_form_ok({
with_fields => {
test_date => 'invalid',
test_time => '25:12',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date and time found');
$mech->submit_form_ok({
with_fields => {
test_date => 'invalid',
test_time => '08:00',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
my $today = DateTime->today;
$mech->submit_form_ok({
with_fields => {
test_date => $today->ymd,
test_time => 'invalid',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid time found');
$mech->submit_form_ok({
with_fields => {
test_date => $today->ymd,
test_time => '08:00',
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/manage");
is(
'' . $mech->find_xpath('//div[@class="datetime"]/text()'),
$today->ymd . ' 08:00:00',
'datetime displayed'
);
is('' . $mech->find_xpath('//div[@class="date_today"]/text()'), 'today', 'today recoginzed');
is(
'' . $mech->find_xpath('//div[@class="time_hm"]/text()'),
'08:00',
'time/format pattern %H:%M works'
);
$mech->follow_link_ok({ url_regex => qr{/2/manage} });
$mech->submit_form_ok({
with_fields => {
test_date => 'invalid',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "invalid"]'),
'error message for invalid date on update found'
);
$mech->submit_form_ok({
with_fields => {
test_date => $today->clone->add(days => 1)->ymd,
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/manage");
is(
'' . $mech->find_xpath('//div[@class="date_today"]/text()'),
'another day',
'tomorrow recognized'
);
+$mech->get_ok("http://localhost/$instance/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=tester} }, 'Add a tester');
+
+$mech->submit_form_ok({
+ with_fields => {
+ test_date => '9.12.2012',
+ test_time => '10:12',
+ },
+ button => 'save',
+});
+$mech->content_lacks('invalid');
+is($mech->value('test_date'), '2012-12-09');
+is($mech->value('test_time'), '10:12:00');
+
+$mech->get_ok("http://localhost/$instance/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=tester} }, 'Add a tester');
+
+$mech->submit_form_ok({
+ with_fields => {
+ test_date => '2013-8-9',
+ test_time => '8:30',
+ },
+ button => 'save',
+});
+$mech->content_lacks('invalid');
+is($mech->value('test_date'), '2013-08-09');
+is($mech->value('test_time'), '08:30:00');
+
done_testing;
|
niner/CiderCMS
|
2f4c74a17e39af38aaccf8a9c268da26176ba122
|
Better error message for non-whitelisted email addresses
|
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index d63c427..a42459c 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,105 +1,105 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
use utf8;
use parent 'Catalyst::Controller';
use Email::Sender::Simple;
use Email::Stuffer;
use Encode qw(encode);
use Hash::Merge qw(merge);
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
unless ($errors) {
$errors = merge(
$self->check_email_whitelist($c, $params),
$self->check_duplicates($c, $params),
);
}
if ($errors) {
$_ = join ', ', @$_ foreach values %$errors;
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
$verify_uri->query_form({email => $params->{email}});
Email::Stuffer->from('noreply@' . $c->stash->{instance})
->to($params->{email})
->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
->text_body(
"Durch Klick auf folgenden Link bestätigen Sie die Anmeldung und, dass Sie
untenstehende Regeln akzeptieren:\n\n"
. $verify_uri
. "\n\n" . $c->config->{registration_rules}
)
->send;
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
sub check_email_whitelist {
my ($self, $c, $params) = @_;
my $whitelist = $c->config->{registration_email_whitelist}
or return;
my %whitelist = map { $_ => 1 } @$whitelist;
return if $whitelist{$params->{email}};
- return { email => ['invalid'] };
+ return { email => ['Emailadresse nicht in der Mitgliederliste'] };
}
sub check_duplicates {
my ($self, $c, $params) = @_;
my $username = $params->{username};
my $context = $c->stash->{context};
my $unverified = $context->attribute('children')->filtered(username => $username);
my $registered = $context->parent->attribute('children')->filtered(username => $username);
return { username => ['bereits vergeben'] } if @$unverified or @$registered;
}
sub verify : CiderCMS('verify_registration') {
my ( $self, $c ) = @_;
my $users = $c->stash->{context}->attribute('children')->filtered(
email => $c->req->params->{email}
);
die "No user found for " . $c->req->params->{email} unless @$users;
my $user = $users->[0];
$user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
}
1;
diff --git a/t/custom_registration.t b/t/custom_registration.t
index f7470ec..a4e8941 100644
--- a/t/custom_registration.t
+++ b/t/custom_registration.t
@@ -1,302 +1,302 @@
use strict;
use warnings;
use utf8;
use Test::More;
BEGIN { $ENV{EMAIL_SENDER_TRANSPORT} = 'Test' }
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use FindBin qw($Bin);
use Regexp::Common qw(URI);
my ($root, $users, $restricted);
setup_test_instance();
test_registration_not_offered();
setup_registration_objects();
test_registration();
done_testing;
sub setup_test_instance {
setup_types();
setup_objects();
}
sub setup_types {
setup_folder_type();
setup_textarea_type();
setup_userlist_type();
setup_user_type();
setup_registration_type();
}
sub setup_folder_type {
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
template => 'folder.zpt',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'restricted',
data_type => 'Boolean',
default_value => 0,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_textarea_type {
CiderCMS::Test->populate_types({
textarea => {
name => 'Textarea',
template => 'textarea.zpt',
page_element => 1,
attributes => [
{
id => 'text',
mandatory => 1,
},
],
},
});
}
sub setup_userlist_type {
CiderCMS::Test->populate_types({
userlist => {
name => 'User list',
attributes => [{
type => 'userlist',
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_user_type {
CiderCMS::Test->populate_types({
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'email',
data_type => 'String',
mandatory => 1,
},
],
},
});
CiderCMS::Test->write_template('user', q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>));
}
sub setup_objects {
$root = $model->get_object($c, 1);
$users = $root->create_child(
attribute => 'children',
type => 'userlist',
data => { title => 'Users' },
);
$restricted = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Restricted', restricted => 1 },
);
}
sub setup_registration_type {
CiderCMS::Test->populate_types({
registration => {
name => 'Registration',
template => 'registration.zpt',
attributes => [
{
id => 'children',
data_type => 'Object',
},
{
id => 'success',
data_type => 'Object',
},
{
id => 'verified',
data_type => 'Object',
},
],
},
});
$model->create_attribute($c, {
type => 'userlist',
id => 'registration',
name => 'Registration',
sort_id => 0,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => '',
});
}
sub setup_registration_objects {
my $registration = $users->create_child(
attribute => 'registration',
type => 'registration',
data => {},
);
my $success = $registration->create_child(
attribute => 'success',
type => 'folder',
data => { title => 'Success' },
);
$success->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! Please check your email.' },
);
my $verified = $registration->create_child(
attribute => 'verified',
type => 'folder',
data => { title => 'Verified' },
);
$verified->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! You are now registered.' },
);
}
sub test_registration_not_offered {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_lacks('Neuen Benutzer registrieren');
}
sub test_registration {
start_registration();
test_validation();
test_success();
test_duplicate();
}
sub start_registration {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_contains('Neuen Benutzer registrieren');
$mech->follow_link_ok({text => 'Neuen Benutzer registrieren'});
}
sub test_validation {
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_contains('missing');
$mech->submit_form_ok({
with_fields => {
password => 'testpass',
email => '[email protected]',
},
});
- $mech->content_contains('invalid');
+ $mech->content_contains('Emailadresse nicht in der Mitgliederliste');
$mech->submit_form_ok({
with_fields => {
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
}
sub test_success {
my @deliveries = Email::Sender::Simple->default_transport->deliveries;
is(scalar @deliveries, 1, 'Confirmation message sent');
my $envelope = $deliveries[0]->{envelope};
is_deeply($envelope->{to}, ['test@localhost'], 'Confirmation message recipient correct');
is($envelope->{from}, "noreply\@$instance", 'Confirmation message sender correct');
my $email = $deliveries[0]->{email};
is(
$email->get_header("Subject"),
"Bestätigung der Anmeldung zu $instance",
'Confirmation message subject correct'
);
my ($link) = $email->get_body =~ /($RE{URI}{HTTP})/;
$mech->get_ok($link);
$mech->content_lacks('Login');
$mech->content_contains('Success! You are now registered.');
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_lacks('Login');
$mech->content_lacks('Invalid username/password');
$mech->title_is('Restricted');
}
sub test_duplicate {
$mech->get_ok("http://localhost/system/logout");
start_registration();
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('bereits vergeben', 'duplicate registered found');
$mech->submit_form_ok({
with_fields => {
username => 'testname2',
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
start_registration();
$mech->submit_form_ok({
with_fields => {
username => 'testname2',
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('bereits vergeben', 'duplicate unverified found');
}
|
niner/CiderCMS
|
1821cc9caaa9a740ec4741485f3e35a2eb2bfc29
|
Check for duplicate user names on registration
|
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index 88cd867..d63c427 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,90 +1,105 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
use utf8;
use parent 'Catalyst::Controller';
use Email::Sender::Simple;
use Email::Stuffer;
use Encode qw(encode);
+use Hash::Merge qw(merge);
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
unless ($errors) {
- $errors = check_email_whitelist($c, $params);
+ $errors = merge(
+ $self->check_email_whitelist($c, $params),
+ $self->check_duplicates($c, $params),
+ );
}
if ($errors) {
$_ = join ', ', @$_ foreach values %$errors;
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
$verify_uri->query_form({email => $params->{email}});
Email::Stuffer->from('noreply@' . $c->stash->{instance})
->to($params->{email})
->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
->text_body(
"Durch Klick auf folgenden Link bestätigen Sie die Anmeldung und, dass Sie
untenstehende Regeln akzeptieren:\n\n"
. $verify_uri
. "\n\n" . $c->config->{registration_rules}
)
->send;
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
sub check_email_whitelist {
- my ($c, $params) = @_;
+ my ($self, $c, $params) = @_;
my $whitelist = $c->config->{registration_email_whitelist}
or return;
my %whitelist = map { $_ => 1 } @$whitelist;
return if $whitelist{$params->{email}};
return { email => ['invalid'] };
}
+sub check_duplicates {
+ my ($self, $c, $params) = @_;
+
+ my $username = $params->{username};
+ my $context = $c->stash->{context};
+
+ my $unverified = $context->attribute('children')->filtered(username => $username);
+ my $registered = $context->parent->attribute('children')->filtered(username => $username);
+
+ return { username => ['bereits vergeben'] } if @$unverified or @$registered;
+}
+
sub verify : CiderCMS('verify_registration') {
my ( $self, $c ) = @_;
my $users = $c->stash->{context}->attribute('children')->filtered(
email => $c->req->params->{email}
);
die "No user found for " . $c->req->params->{email} unless @$users;
my $user = $users->[0];
$user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
}
1;
-
diff --git a/t/custom_registration.t b/t/custom_registration.t
index f019d29..f7470ec 100644
--- a/t/custom_registration.t
+++ b/t/custom_registration.t
@@ -1,269 +1,302 @@
use strict;
use warnings;
use utf8;
use Test::More;
BEGIN { $ENV{EMAIL_SENDER_TRANSPORT} = 'Test' }
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use FindBin qw($Bin);
use Regexp::Common qw(URI);
my ($root, $users, $restricted);
setup_test_instance();
test_registration_not_offered();
setup_registration_objects();
test_registration();
done_testing;
sub setup_test_instance {
setup_types();
setup_objects();
}
sub setup_types {
setup_folder_type();
setup_textarea_type();
setup_userlist_type();
setup_user_type();
setup_registration_type();
}
sub setup_folder_type {
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
template => 'folder.zpt',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'restricted',
data_type => 'Boolean',
default_value => 0,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_textarea_type {
CiderCMS::Test->populate_types({
textarea => {
name => 'Textarea',
template => 'textarea.zpt',
page_element => 1,
attributes => [
{
id => 'text',
mandatory => 1,
},
],
},
});
}
sub setup_userlist_type {
CiderCMS::Test->populate_types({
userlist => {
name => 'User list',
attributes => [{
type => 'userlist',
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_user_type {
CiderCMS::Test->populate_types({
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'email',
data_type => 'String',
mandatory => 1,
},
],
},
});
CiderCMS::Test->write_template('user', q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>));
}
sub setup_objects {
$root = $model->get_object($c, 1);
$users = $root->create_child(
attribute => 'children',
type => 'userlist',
data => { title => 'Users' },
);
$restricted = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Restricted', restricted => 1 },
);
}
sub setup_registration_type {
CiderCMS::Test->populate_types({
registration => {
name => 'Registration',
template => 'registration.zpt',
attributes => [
{
id => 'children',
data_type => 'Object',
},
{
id => 'success',
data_type => 'Object',
},
{
id => 'verified',
data_type => 'Object',
},
],
},
});
$model->create_attribute($c, {
type => 'userlist',
id => 'registration',
name => 'Registration',
sort_id => 0,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => '',
});
}
sub setup_registration_objects {
my $registration = $users->create_child(
attribute => 'registration',
type => 'registration',
data => {},
);
my $success = $registration->create_child(
attribute => 'success',
type => 'folder',
data => { title => 'Success' },
);
$success->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! Please check your email.' },
);
my $verified = $registration->create_child(
attribute => 'verified',
type => 'folder',
data => { title => 'Verified' },
);
$verified->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! You are now registered.' },
);
}
sub test_registration_not_offered {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_lacks('Neuen Benutzer registrieren');
}
sub test_registration {
start_registration();
test_validation();
test_success();
+ test_duplicate();
}
sub start_registration {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_contains('Neuen Benutzer registrieren');
$mech->follow_link_ok({text => 'Neuen Benutzer registrieren'});
}
sub test_validation {
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_contains('missing');
$mech->submit_form_ok({
with_fields => {
password => 'testpass',
email => '[email protected]',
},
});
$mech->content_contains('invalid');
$mech->submit_form_ok({
with_fields => {
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
}
sub test_success {
my @deliveries = Email::Sender::Simple->default_transport->deliveries;
is(scalar @deliveries, 1, 'Confirmation message sent');
my $envelope = $deliveries[0]->{envelope};
is_deeply($envelope->{to}, ['test@localhost'], 'Confirmation message recipient correct');
is($envelope->{from}, "noreply\@$instance", 'Confirmation message sender correct');
my $email = $deliveries[0]->{email};
is(
$email->get_header("Subject"),
"Bestätigung der Anmeldung zu $instance",
'Confirmation message subject correct'
);
my ($link) = $email->get_body =~ /($RE{URI}{HTTP})/;
$mech->get_ok($link);
$mech->content_lacks('Login');
$mech->content_contains('Success! You are now registered.');
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_lacks('Login');
$mech->content_lacks('Invalid username/password');
$mech->title_is('Restricted');
}
+
+sub test_duplicate {
+ $mech->get_ok("http://localhost/system/logout");
+ start_registration();
+ $mech->submit_form_ok({
+ with_fields => {
+ username => 'testname',
+ password => 'testpass',
+ email => 'test@localhost',
+ },
+ });
+ $mech->content_contains('bereits vergeben', 'duplicate registered found');
+
+ $mech->submit_form_ok({
+ with_fields => {
+ username => 'testname2',
+ password => 'testpass',
+ email => 'test@localhost',
+ },
+ });
+ $mech->content_contains('Success! Please check your email.');
+
+ start_registration();
+ $mech->submit_form_ok({
+ with_fields => {
+ username => 'testname2',
+ password => 'testpass',
+ email => 'test@localhost',
+ },
+ });
+ $mech->content_contains('bereits vergeben', 'duplicate unverified found');
+}
|
niner/CiderCMS
|
ff750a08d6934410d6e3f5952dc5816891b46e6f
|
Implement an email whitelist for registration
|
diff --git a/cidercms_test.yml b/cidercms_test.yml
new file mode 100644
index 0000000..7013434
--- /dev/null
+++ b/cidercms_test.yml
@@ -0,0 +1,2 @@
+registration_email_whitelist:
+ - test@localhost
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index dfd43fa..88cd867 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,74 +1,90 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
use utf8;
use parent 'Catalyst::Controller';
use Email::Sender::Simple;
use Email::Stuffer;
use Encode qw(encode);
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
+ unless ($errors) {
+ $errors = check_email_whitelist($c, $params);
+ }
if ($errors) {
$_ = join ', ', @$_ foreach values %$errors;
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
$verify_uri->query_form({email => $params->{email}});
Email::Stuffer->from('noreply@' . $c->stash->{instance})
->to($params->{email})
->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
->text_body(
"Durch Klick auf folgenden Link bestätigen Sie die Anmeldung und, dass Sie
untenstehende Regeln akzeptieren:\n\n"
. $verify_uri
. "\n\n" . $c->config->{registration_rules}
)
->send;
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
+sub check_email_whitelist {
+ my ($c, $params) = @_;
+
+ my $whitelist = $c->config->{registration_email_whitelist}
+ or return;
+
+ my %whitelist = map { $_ => 1 } @$whitelist;
+
+ return if $whitelist{$params->{email}};
+
+ return { email => ['invalid'] };
+}
+
sub verify : CiderCMS('verify_registration') {
my ( $self, $c ) = @_;
my $users = $c->stash->{context}->attribute('children')->filtered(
email => $c->req->params->{email}
);
die "No user found for " . $c->req->params->{email} unless @$users;
my $user = $users->[0];
$user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
}
1;
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index e9e409a..0ac75d3 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,185 +1,187 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
+ $ENV{ CIDERCMS_CONFIG_LOCAL_SUFFIX } = 'test';
+
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
my $c = CiderCMS->new;
my $model = $c->model('DB');
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
sub write_template {
my ($self, $file, $contents) = @_;
write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
}
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
}
1;
diff --git a/t/custom_registration.t b/t/custom_registration.t
index be393ac..f019d29 100644
--- a/t/custom_registration.t
+++ b/t/custom_registration.t
@@ -1,251 +1,269 @@
use strict;
use warnings;
use utf8;
use Test::More;
BEGIN { $ENV{EMAIL_SENDER_TRANSPORT} = 'Test' }
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use FindBin qw($Bin);
use Regexp::Common qw(URI);
my ($root, $users, $restricted);
setup_test_instance();
test_registration_not_offered();
setup_registration_objects();
test_registration();
done_testing;
sub setup_test_instance {
setup_types();
setup_objects();
}
sub setup_types {
setup_folder_type();
setup_textarea_type();
setup_userlist_type();
setup_user_type();
setup_registration_type();
}
sub setup_folder_type {
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
template => 'folder.zpt',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'restricted',
data_type => 'Boolean',
default_value => 0,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_textarea_type {
CiderCMS::Test->populate_types({
textarea => {
name => 'Textarea',
template => 'textarea.zpt',
page_element => 1,
attributes => [
{
id => 'text',
mandatory => 1,
},
],
},
});
}
sub setup_userlist_type {
CiderCMS::Test->populate_types({
userlist => {
name => 'User list',
attributes => [{
type => 'userlist',
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_user_type {
CiderCMS::Test->populate_types({
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'email',
data_type => 'String',
mandatory => 1,
},
],
},
});
CiderCMS::Test->write_template('user', q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>));
}
sub setup_objects {
$root = $model->get_object($c, 1);
$users = $root->create_child(
attribute => 'children',
type => 'userlist',
data => { title => 'Users' },
);
$restricted = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Restricted', restricted => 1 },
);
}
sub setup_registration_type {
CiderCMS::Test->populate_types({
registration => {
name => 'Registration',
template => 'registration.zpt',
attributes => [
{
id => 'children',
data_type => 'Object',
},
{
id => 'success',
data_type => 'Object',
},
{
id => 'verified',
data_type => 'Object',
},
],
},
});
$model->create_attribute($c, {
type => 'userlist',
id => 'registration',
name => 'Registration',
sort_id => 0,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => '',
});
}
sub setup_registration_objects {
my $registration = $users->create_child(
attribute => 'registration',
type => 'registration',
data => {},
);
my $success = $registration->create_child(
attribute => 'success',
type => 'folder',
data => { title => 'Success' },
);
$success->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! Please check your email.' },
);
my $verified = $registration->create_child(
attribute => 'verified',
type => 'folder',
data => { title => 'Verified' },
);
$verified->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! You are now registered.' },
);
}
sub test_registration_not_offered {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_lacks('Neuen Benutzer registrieren');
}
sub test_registration {
+ start_registration();
+ test_validation();
+ test_success();
+}
+
+sub start_registration {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_contains('Neuen Benutzer registrieren');
$mech->follow_link_ok({text => 'Neuen Benutzer registrieren'});
+}
+
+sub test_validation {
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_contains('missing');
+ $mech->submit_form_ok({
+ with_fields => {
+ password => 'testpass',
+ email => '[email protected]',
+ },
+ });
+ $mech->content_contains('invalid');
$mech->submit_form_ok({
with_fields => {
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
+}
+sub test_success {
my @deliveries = Email::Sender::Simple->default_transport->deliveries;
is(scalar @deliveries, 1, 'Confirmation message sent');
my $envelope = $deliveries[0]->{envelope};
is_deeply($envelope->{to}, ['test@localhost'], 'Confirmation message recipient correct');
is($envelope->{from}, "noreply\@$instance", 'Confirmation message sender correct');
my $email = $deliveries[0]->{email};
is(
$email->get_header("Subject"),
"Bestätigung der Anmeldung zu $instance",
'Confirmation message subject correct'
);
my ($link) = $email->get_body =~ /($RE{URI}{HTTP})/;
$mech->get_ok($link);
$mech->content_lacks('Login');
$mech->content_contains('Success! You are now registered.');
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_lacks('Login');
$mech->content_lacks('Invalid username/password');
$mech->title_is('Restricted');
}
|
niner/CiderCMS
|
a8af13fbda0ba7594afd2c1c59b989b41121a68c
|
Unbreak /system/types with CIDERCMS_INSTANCE
|
diff --git a/lib/CiderCMS.pm b/lib/CiderCMS.pm
index 52af7da..4bb1659 100644
--- a/lib/CiderCMS.pm
+++ b/lib/CiderCMS.pm
@@ -1,188 +1,188 @@
package CiderCMS;
use strict;
use warnings;
use Catalyst::Runtime 5.80;
use Catalyst::DispatchType::CiderCMS;
# Set flags and add plugins for the application
#
# ConfigLoader: will load the configuration from a Config::General file in the
# application's home directory
# Static::Simple: will serve static files from the application's root
# directory
use parent qw/Catalyst/;
use Catalyst qw/
Unicode::Encoding
ConfigLoader
Static::Simple
FormValidator
Authentication
Session
Session::State::Cookie
Session::Store::FastMmap
/;
our $VERSION = '0.01';
# Configure the application.
#
# Note that settings in cidercms.conf (or other external
# configuration file that you set up manually) take precedence
# over this when using ConfigLoader. Thus configuration
# details given here can function as a default configuration,
# with an external configuration file acting as an override for
# local deployment.
__PACKAGE__->config(
name => 'CiderCMS',
encoding => 'UTF-8',
);
# Start the application
__PACKAGE__->setup();
=head1 NAME
CiderCMS - Catalyst based application
=head1 SYNOPSIS
script/cidercms_server.pl
=head1 DESCRIPTION
CiderCMS is a very flexible CMS.
=head1 METHODS
=head2 prepare_path
Checks for an CIDERCMS_INSTANCE environment variable and prepends it to the path if present.
=cut
sub prepare_path {
my ($self, @args) = @_;
$self->maybe::next::method(@args);
my $uri_raw = $self->request->uri->clone;
if (my $instance = $ENV{CIDERCMS_INSTANCE}) {
my $uri = $uri_raw->clone;
my $path = $instance . $uri->path;
$uri->path($path);
- $self->request->path($path) unless $self->req->path =~ /\Asystem/;
+ $self->request->path($path);
$uri->path_query('');
$uri->fragment(undef);
$self->stash({
uri_instance => $uri,
uri_static => "$uri/static",
uri_raw => $uri_raw,
});
}
else {
$self->stash->{uri_raw} = $uri_raw;
}
return;
}
if ($ENV{CIDERCMS_INSTANCE}) {
__PACKAGE__->config->{static}{include_path} = [
__PACKAGE__->config->{root} . '/instances/',
__PACKAGE__->config->{root},
];
}
=head2 uri_for_instance(@path)
Creates an URI relative to the current instance's root
=cut
sub uri_for_instance {
my ($self, @path) = @_;
return ($self->stash->{uri_instance} ||= $self->uri_for('/') . $self->stash->{instance}) . (@path ? join '/', '', @path : '');
}
=head2 uri_static_for_instance()
Returns an URI for static files for this instance
=cut
sub uri_static_for_instance {
my ($self, @path) = @_;
return join '/', ($self->stash->{uri_static} or $self->uri_for('/') . (join '/', 'instances', $self->stash->{instance}, 'static')), @path;
}
=head2 fs_path_for_instance()
Returns a file system path for the current instance's root
=cut
sub fs_path_for_instance {
my ($self) = @_;
return $self->config->{root} . '/instances/' . $self->stash->{instance} . '/static';
}
=head2 register_management_action
Controllers may register subroutines returning additional actions for the management interface dynamically.
For example:
CiderCMS->register_management_action(__PACKAGE__, sub {
my ($self, $c) = @_;
return {title => 'Foo', uri => $c->uri_for('foo')}, { ... };
});
=cut
my %management_actions;
sub register_management_action {
my ($self, $package, $action_creator) = @_;
$management_actions{$package} = $action_creator;
return;
}
=head2 management_actions
Returns the registered management actions
=cut
sub management_actions {
my ($self) = @_;
return \%management_actions;
}
=head1 SEE ALSO
L<CiderCMS::Controller::Root>, L<Catalyst>
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Controller/System.pm b/lib/CiderCMS/Controller/System.pm
index ffa630c..eaa0245 100644
--- a/lib/CiderCMS/Controller/System.pm
+++ b/lib/CiderCMS/Controller/System.pm
@@ -1,89 +1,95 @@
package CiderCMS::Controller::System;
use strict;
use warnings;
use parent 'Catalyst::Controller';
=head1 NAME
CiderCMS::Controller::System - Catalyst Controller
=head1 DESCRIPTION
Meta operations of the instance, e.g. everything not related to content manipulation.
=head1 METHODS
=head2 init
PathPart that sets up the current instance.
=cut
sub init : Chained('/') PathPart('') CaptureArgs(1) {
my ( $self, $c, $instance ) = @_;
$c->stash->{instance} = $instance;
my $model = $c->model('DB');
$model->initialize($c);
$c->stash({
uri_manage_types => $c->uri_for_instance('system/types'),
uri_manage_content => $model->get_object($c, 1)->uri_management,
});
return;
}
=head2 create
Create a new CiderCMS instance, e.g. a new website.
=cut
sub create :Local :Args(0) {
my ( $self, $c ) = @_;
my $valid = $c->form({
required => [qw(id title)],
});
if ($valid) {
$c->model('DB')->create_instance($c, scalar $valid->valid());
$c->stash({ instance => $valid->valid('id') });
return $c->res->redirect($c->uri_for_instance('manage'));
}
else {
$c->stash({ template => 'system/create.zpt' });
}
return;
}
=head2 logout
Ends the user's session
=cut
sub logout : Local :Args(0) {
my ( $self, $c ) = @_;
$c->logout;
return $c->res->redirect($c->req->referer) if $c->req->referer;
return $c->res->body('User logged out');
}
+sub instance_logout : PathPart('system/logout') Chained('init') {
+ my ( $self, $c ) = @_;
+
+ $c->forward('logout');
+}
+
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
|
niner/CiderCMS
|
04e4146c11bb762bd19171fd8e40ae84766ad412
|
Except /system from adding the instance path to allow /system/logout
|
diff --git a/lib/CiderCMS.pm b/lib/CiderCMS.pm
index 4bb1659..52af7da 100644
--- a/lib/CiderCMS.pm
+++ b/lib/CiderCMS.pm
@@ -1,188 +1,188 @@
package CiderCMS;
use strict;
use warnings;
use Catalyst::Runtime 5.80;
use Catalyst::DispatchType::CiderCMS;
# Set flags and add plugins for the application
#
# ConfigLoader: will load the configuration from a Config::General file in the
# application's home directory
# Static::Simple: will serve static files from the application's root
# directory
use parent qw/Catalyst/;
use Catalyst qw/
Unicode::Encoding
ConfigLoader
Static::Simple
FormValidator
Authentication
Session
Session::State::Cookie
Session::Store::FastMmap
/;
our $VERSION = '0.01';
# Configure the application.
#
# Note that settings in cidercms.conf (or other external
# configuration file that you set up manually) take precedence
# over this when using ConfigLoader. Thus configuration
# details given here can function as a default configuration,
# with an external configuration file acting as an override for
# local deployment.
__PACKAGE__->config(
name => 'CiderCMS',
encoding => 'UTF-8',
);
# Start the application
__PACKAGE__->setup();
=head1 NAME
CiderCMS - Catalyst based application
=head1 SYNOPSIS
script/cidercms_server.pl
=head1 DESCRIPTION
CiderCMS is a very flexible CMS.
=head1 METHODS
=head2 prepare_path
Checks for an CIDERCMS_INSTANCE environment variable and prepends it to the path if present.
=cut
sub prepare_path {
my ($self, @args) = @_;
$self->maybe::next::method(@args);
my $uri_raw = $self->request->uri->clone;
if (my $instance = $ENV{CIDERCMS_INSTANCE}) {
my $uri = $uri_raw->clone;
my $path = $instance . $uri->path;
$uri->path($path);
- $self->request->path($path);
+ $self->request->path($path) unless $self->req->path =~ /\Asystem/;
$uri->path_query('');
$uri->fragment(undef);
$self->stash({
uri_instance => $uri,
uri_static => "$uri/static",
uri_raw => $uri_raw,
});
}
else {
$self->stash->{uri_raw} = $uri_raw;
}
return;
}
if ($ENV{CIDERCMS_INSTANCE}) {
__PACKAGE__->config->{static}{include_path} = [
__PACKAGE__->config->{root} . '/instances/',
__PACKAGE__->config->{root},
];
}
=head2 uri_for_instance(@path)
Creates an URI relative to the current instance's root
=cut
sub uri_for_instance {
my ($self, @path) = @_;
return ($self->stash->{uri_instance} ||= $self->uri_for('/') . $self->stash->{instance}) . (@path ? join '/', '', @path : '');
}
=head2 uri_static_for_instance()
Returns an URI for static files for this instance
=cut
sub uri_static_for_instance {
my ($self, @path) = @_;
return join '/', ($self->stash->{uri_static} or $self->uri_for('/') . (join '/', 'instances', $self->stash->{instance}, 'static')), @path;
}
=head2 fs_path_for_instance()
Returns a file system path for the current instance's root
=cut
sub fs_path_for_instance {
my ($self) = @_;
return $self->config->{root} . '/instances/' . $self->stash->{instance} . '/static';
}
=head2 register_management_action
Controllers may register subroutines returning additional actions for the management interface dynamically.
For example:
CiderCMS->register_management_action(__PACKAGE__, sub {
my ($self, $c) = @_;
return {title => 'Foo', uri => $c->uri_for('foo')}, { ... };
});
=cut
my %management_actions;
sub register_management_action {
my ($self, $package, $action_creator) = @_;
$management_actions{$package} = $action_creator;
return;
}
=head2 management_actions
Returns the registered management actions
=cut
sub management_actions {
my ($self) = @_;
return \%management_actions;
}
=head1 SEE ALSO
L<CiderCMS::Controller::Root>, L<Catalyst>
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
|
niner/CiderCMS
|
3f1f339fa6f7d54ba2124b76302559615a3a08a0
|
Rules in registration email
|
diff --git a/cidercms.yml b/cidercms.yml
index f1d5ff6..00f96d1 100644
--- a/cidercms.yml
+++ b/cidercms.yml
@@ -1,10 +1,43 @@
name: CiderCMS
Plugin::Authentication:
default:
credential:
class: Password
password_type: hashed
password_hash_type: SHA-256
store:
class: CiderCMS
+
+registration_rules: |
+ Regeln
+
+ Eintragungen sind bis maximal 12 Stunden vor dem jeweiligen Termin möglich.
+
+ Minimum der Reservierungsdauer sind 30 Minuten.
+
+ Tank- und Pflegezeiten unmittelbar nach dem Flug sind in die Reservierung mit
+ einzurechnen.
+
+ Reservierungen, bei denen das Flugzeug über Nacht nicht im Heimathangar steht,
+ sind mit dem Linzer Vorstand abzustimmen.
+
+ Wenn das Flugzeug nicht innerhalb der ersten 15 Minuten des Reservierungs-
+ zeitraumes durch den Reservierenden in Anspruch genommen wird, verfällt die
+ Reservierung und das Flugzeug steht im betreffenden Zeitraum frei zur Verfügung.
+ Zeitliche Ãberziehungen (zu spätes Zurückkommen) gehen zu Lasten der nächsten
+ Reservierung (sollte unmittelbar eine anschlieÃen).
+
+ Nicht âreservierteâ Flugzeiten können so wie bisher in Anspruch genommen werden.
+
+ Der Pilot muss sich vor Flugantritt davon überzeugen, dass für den von ihm
+ geplanten Zeitraum keine Reservierung vorliegt. Das Flugzeug muss aber
+ spätestens bei Beginn des nächsten Reservierungszeitraumes bereitstehen
+ (Tankzeiten unmittelbar nach dem Flug sind mit einzurechnen).
+
+ Reservierungen, die nicht in Anspruch genommen werden können, müssen vom
+ Reservierenden so lange als möglich im Vorhinein wieder storniert werden.
+ Steht ein Flugzeug aus z.B. Wartungsgründen nicht zur Verfügung, so ist dies
+ in der Reservierungsliste mit âUNKLARâ gekennzeichnet. Bei bereits vorliegenden
+ Reservierungen werden die Betroffenen per Mail (Adresse bei der Registrierung
+ angegeben) verständigt.
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index 90abd18..dfd43fa 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,108 +1,74 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
use utf8;
use parent 'Catalyst::Controller';
use Email::Sender::Simple;
use Email::Stuffer;
use Encode qw(encode);
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
if ($errors) {
$_ = join ', ', @$_ foreach values %$errors;
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
$verify_uri->query_form({email => $params->{email}});
Email::Stuffer->from('noreply@' . $c->stash->{instance})
->to($params->{email})
->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
->text_body(
"Durch Klick auf folgenden Link bestätigen Sie die Anmeldung und, dass Sie
untenstehende Regeln akzeptieren:\n\n"
. $verify_uri
- . <<RULES
-
-
-Regeln
-
-Eintragungen sind bis maximal 12 Stunden vor dem jeweiligen Termin möglich.
-
-Minimum der Reservierungsdauer sind 30 Minuten.
-
-Tank- und Pflegezeiten unmittelbar nach dem Flug sind in die Reservierung mit
-einzurechnen.
-
-Reservierungen, bei denen das Flugzeug über Nacht nicht im Heimathangar steht,
-sind mit dem Linzer Vorstand abzustimmen.
-
-Wenn das Flugzeug nicht innerhalb der ersten 15 Minuten des Reservierungs-
-zeitraumes durch den Reservierenden in Anspruch genommen wird, verfällt die
-Reservierung und das Flugzeug steht im betreffenden Zeitraum frei zur Verfügung.
-Zeitliche Ãberziehungen (zu spätes Zurückkommen) gehen zu Lasten der nächsten
-Reservierung (sollte unmittelbar eine anschlieÃen).
-
-Nicht âreservierteâ Flugzeiten können so wie bisher in Anspruch genommen werden.
-
-Der Pilot muss sich vor Flugantritt davon überzeugen, dass für den von ihm
-geplanten Zeitraum keine Reservierung vorliegt. Das Flugzeug muss aber
-spätestens bei Beginn des nächsten Reservierungszeitraumes bereitstehen
-(Tankzeiten unmittelbar nach dem Flug sind mit einzurechnen).
-
-Reservierungen, die nicht in Anspruch genommen werden können, müssen vom
-Reservierenden so lange als möglich im Vorhinein wieder storniert werden.
-Steht ein Flugzeug aus z.B. Wartungsgründen nicht zur Verfügung, so ist dies
-in der Reservierungsliste mit âUNKLARâ gekennzeichnet. Bei bereits vorliegenden
-Reservierungen werden die Betroffenen per Mail (Adresse bei der Registrierung
-angegeben) verständigt.
-RULES
+ . "\n\n" . $c->config->{registration_rules}
)
->send;
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
sub verify : CiderCMS('verify_registration') {
my ( $self, $c ) = @_;
my $users = $c->stash->{context}->attribute('children')->filtered(
email => $c->req->params->{email}
);
die "No user found for " . $c->req->params->{email} unless @$users;
my $user = $users->[0];
$user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
}
1;
|
niner/CiderCMS
|
87f5754cad549eb69fd70678417eda198b3d617e
|
Rules in registration email
|
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index 74fb38e..90abd18 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,72 +1,108 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
use utf8;
use parent 'Catalyst::Controller';
use Email::Sender::Simple;
use Email::Stuffer;
use Encode qw(encode);
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
if ($errors) {
$_ = join ', ', @$_ foreach values %$errors;
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
$verify_uri->query_form({email => $params->{email}});
Email::Stuffer->from('noreply@' . $c->stash->{instance})
->to($params->{email})
->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
->text_body(
- "Bitte klicken Sie auf den folgenden Link um die Anmeldung zu bestätigen:\n"
+ "Durch Klick auf folgenden Link bestätigen Sie die Anmeldung und, dass Sie
+untenstehende Regeln akzeptieren:\n\n"
. $verify_uri
+ . <<RULES
+
+
+Regeln
+
+Eintragungen sind bis maximal 12 Stunden vor dem jeweiligen Termin möglich.
+
+Minimum der Reservierungsdauer sind 30 Minuten.
+
+Tank- und Pflegezeiten unmittelbar nach dem Flug sind in die Reservierung mit
+einzurechnen.
+
+Reservierungen, bei denen das Flugzeug über Nacht nicht im Heimathangar steht,
+sind mit dem Linzer Vorstand abzustimmen.
+
+Wenn das Flugzeug nicht innerhalb der ersten 15 Minuten des Reservierungs-
+zeitraumes durch den Reservierenden in Anspruch genommen wird, verfällt die
+Reservierung und das Flugzeug steht im betreffenden Zeitraum frei zur Verfügung.
+Zeitliche Ãberziehungen (zu spätes Zurückkommen) gehen zu Lasten der nächsten
+Reservierung (sollte unmittelbar eine anschlieÃen).
+
+Nicht âreservierteâ Flugzeiten können so wie bisher in Anspruch genommen werden.
+
+Der Pilot muss sich vor Flugantritt davon überzeugen, dass für den von ihm
+geplanten Zeitraum keine Reservierung vorliegt. Das Flugzeug muss aber
+spätestens bei Beginn des nächsten Reservierungszeitraumes bereitstehen
+(Tankzeiten unmittelbar nach dem Flug sind mit einzurechnen).
+
+Reservierungen, die nicht in Anspruch genommen werden können, müssen vom
+Reservierenden so lange als möglich im Vorhinein wieder storniert werden.
+Steht ein Flugzeug aus z.B. Wartungsgründen nicht zur Verfügung, so ist dies
+in der Reservierungsliste mit âUNKLARâ gekennzeichnet. Bei bereits vorliegenden
+Reservierungen werden die Betroffenen per Mail (Adresse bei der Registrierung
+angegeben) verständigt.
+RULES
)
->send;
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
sub verify : CiderCMS('verify_registration') {
my ( $self, $c ) = @_;
my $users = $c->stash->{context}->attribute('children')->filtered(
email => $c->req->params->{email}
);
die "No user found for " . $c->req->params->{email} unless @$users;
my $user = $users->[0];
$user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
}
1;
|
niner/CiderCMS
|
48be80811b17c7a4e0409557a399c46dc670481b
|
Require authenticated user for cancelling a reservation
|
diff --git a/lib/CiderCMS/Controller/Custom/Reservation.pm b/lib/CiderCMS/Controller/Custom/Reservation.pm
index acdb4b5..c3f9949 100644
--- a/lib/CiderCMS/Controller/Custom/Reservation.pm
+++ b/lib/CiderCMS/Controller/Custom/Reservation.pm
@@ -1,153 +1,155 @@
package CiderCMS::Controller::Custom::Reservation;
use strict;
use warnings;
use parent 'Catalyst::Controller';
use DateTime::Format::ISO8601;
use DateTime::Span;
use Hash::Merge qw(merge);
=head2 reserve
Reserve the displayed plane.
=cut
sub reserve : CiderCMS('reserve') {
my ( $self, $c ) = @_;
$c->detach('/user/login') unless $c->user;
my $params = $c->req->params;
my $save = delete $params->{save};
my $object = $c->stash->{context}->new_child(
attribute => 'reservations',
type => 'reservation',
);
my $errors = {};
if ($save) {
$errors = $object->validate($params);
unless ($errors) {
$params->{start_time} = sprintf '%02i:%02i', split /:/, $params->{start_time};
my $start = DateTime::Format::ISO8601->new(
base_datetime => DateTime->now(time_zone => 'floating'),
)->parse_datetime(
"$params->{start_date}T$params->{start_time}"
);
$errors = merge(
$self->check_time_limit($c, $start),
$self->check_conflicts($c, $start, $params->{end}),
);
}
unless ($errors) {
$object->insert({data => $params});
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
$_ = join ', ', @$_ foreach values %$errors;
}
else {
$object->init_defaults;
}
$c->stash->{reservation} = 1;
$c->stash->{reserve} = 1;
my $content = $c->view('Petal')->render_template(
$c,
{
user => $c->user->get('name'),
%{ $c->stash },
%$params,
template => 'custom/reservation/reserve.zpt',
uri_cancel => $c->stash->{context}->uri . '/cancel',
errors => $errors,
},
);
$c->stash({
template => 'index.zpt',
content => $content,
});
return;
}
=head3 check_time_limit($c, $start)
=cut
sub check_time_limit {
my ($self, $c, $start) = @_;
my $time_limit = $c->stash->{context}->property('reservation_time_limit', undef);
return unless $time_limit;
my $limit = DateTime->now(time_zone => 'local')
->set_time_zone('floating')
->add(hours => $time_limit);
return {start => ['too close']} if $start->datetime lt $limit->datetime;
return;
}
=head3 check_conflicts($c, $start)
=cut
sub check_conflicts {
my ($self, $c, $start, $end) = @_;
my $reservations = $c->stash->{context}->attribute('reservations');
my $new = create_datetime_span($start, $end);
foreach my $existing (@{ $reservations->filtered(cancelled_by => undef) }) {
my $existing = create_datetime_span(
$existing->attribute('start')->object,
$existing->property('end')
);
if ($new->intersects($existing)) {
return {start => ['conflicting existent reservation']};
}
}
return;
}
=head4 create_datetime_span($start, $end)
=cut
sub create_datetime_span {
my ($start, $end) = @_;
my ($end_h, $end_m) = split /:/, $end;
return DateTime::Span->from_datetimes(
start => $start,
end => $start->clone->set_hour($end_h)->set_minute($end_m)->subtract(seconds => 1)
);
}
=head2 cancel
Cancel the given reservation.
=cut
sub cancel : CiderCMS('cancel') Args(1) {
my ($self, $c, $id) = @_;
+ $c->detach('/user/login') unless $c->user;
+
my $context = $c->stash->{context};
my $reservation = $c->model('DB')->get_object($c, $id, $context->{level} + 1);
if ($reservation->{parent} == $context->{id}) {
$reservation->set_property(cancelled_by => $c->user->get('name'));
$reservation->update;
}
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
1;
diff --git a/t/custom_reservation.t b/t/custom_reservation.t
index f207cef..cb49c22 100644
--- a/t/custom_reservation.t
+++ b/t/custom_reservation.t
@@ -1,282 +1,290 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
repetitive => 1,
},
],
},
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'name',
data_type => 'String',
},
],
},
reservation => {
name => 'Reservation',
page_element => 1,
attributes => [
{
id => 'start',
data_type => 'DateTime',
mandatory => 1,
},
{
id => 'end',
data_type => 'Time',
mandatory => 1,
},
{
id => 'user',
data_type => 'String',
},
{
id => 'info',
data_type => 'String',
},
{
id => 'cancelled_by',
data_type => 'String',
},
],
},
airplane => {
name => 'Airplane',
page_element => 1,
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'reservations',
data_type => 'Object',
repetitive => 1,
},
{
id => 'reservation_time_limit',
data_type => 'Integer',
},
],
template => 'airplane.zpt'
},
});
my $root = $model->get_object($c, 1);
my $users = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Users' },
);
$users->create_child(
attribute => 'children',
type => 'user',
data => {
username => 'test',
name => 'test',
password => 'test',
},
);
my $airplanes = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Airplanes' },
);
my $dimona = $airplanes->create_child(
attribute => 'children',
type => 'airplane',
data => {
title => 'Dimona',
},
);
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->content_contains('Keine Reservierungen eingetragen.');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
$mech->content_lacks('Keine Reservierungen eingetragen.');
ok($mech->find_xpath(qq{//td[span="Heute"]}), "Today's reservation listed");
ok($mech->find_xpath(qq{//td[text()="test"]}), 'reserving user listed');
ok($mech->find_xpath(qq{//td[text()="Testflug"]}), 'Info listed');
$date->add(days => 1);
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
ok($mech->find_xpath(q{//td[span="Heute"]}), "Today's reservation still listed");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
$mech->get_ok(
$mech->find_xpath(q{//tr[td="Heute"]/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
is('' . $mech->find_xpath(q{//td[text()="Heute"]}), '', "Today's reservation gone");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/6/manage");
is($mech->value('cancelled_by'), 'test');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "conflicting existent reservation"]'),
'error message for conflict with existent reservation found'
);
+ $mech->get_ok("http://localhost/system/logout");
+ $mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->get_ok(
$mech->find_xpath(q{//tr/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
+ $mech->submit_form_ok({
+ with_fields => {
+ username => 'test',
+ password => 'test',
+ },
+ });
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
not($mech->find_xpath('//span[text() = "conflicting existent reservation"]')),
'error message for conflict with existent reservation not found anymore'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
# test error handling
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => 'invalid',
start_time => 'nonsense',
end => 'forget',
info => '',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
$model->dbh->rollback;
});
$model->txn_do(sub {
# Update to test advance time limit
$dimona->set_property(reservation_time_limit => 24);
$dimona->update;
my $now = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->clone->add(hours => 1)->hms,
end => $now->clone->add(hours => 2)->hms,
info => 'too close',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "too close"]'), 'error message for too close date found');
$now = DateTime->now->add(days => 2)->add(hours => 4);
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->hms,
end => $now->clone->add(hours => 1)->hms,
info => 'too close',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too close"]'),
'',
'error message for too close date gone'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
ok($mech->find_xpath(qq{//p[text()="Frei"]}), "No reservation active for now");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->subtract(hours => 1)->hms(':'),
end => $date->clone->add(hours => 2)->hour . ':00',
info => 'Testflug',
},
button => 'save',
});
is('' . $mech->find_xpath(qq{//p[text()="Frei"]}), '', "Reservation active for now");
$model->dbh->rollback;
});
done_testing;
|
niner/CiderCMS
|
d430a130d0bbbaf322443fc05f1cf1ea3bb587e6
|
Don't conflict with cancelled reservations
|
diff --git a/lib/CiderCMS/Controller/Custom/Reservation.pm b/lib/CiderCMS/Controller/Custom/Reservation.pm
index b6afcdf..acdb4b5 100644
--- a/lib/CiderCMS/Controller/Custom/Reservation.pm
+++ b/lib/CiderCMS/Controller/Custom/Reservation.pm
@@ -1,153 +1,153 @@
package CiderCMS::Controller::Custom::Reservation;
use strict;
use warnings;
use parent 'Catalyst::Controller';
use DateTime::Format::ISO8601;
use DateTime::Span;
use Hash::Merge qw(merge);
=head2 reserve
Reserve the displayed plane.
=cut
sub reserve : CiderCMS('reserve') {
my ( $self, $c ) = @_;
$c->detach('/user/login') unless $c->user;
my $params = $c->req->params;
my $save = delete $params->{save};
my $object = $c->stash->{context}->new_child(
attribute => 'reservations',
type => 'reservation',
);
my $errors = {};
if ($save) {
$errors = $object->validate($params);
unless ($errors) {
$params->{start_time} = sprintf '%02i:%02i', split /:/, $params->{start_time};
my $start = DateTime::Format::ISO8601->new(
base_datetime => DateTime->now(time_zone => 'floating'),
)->parse_datetime(
"$params->{start_date}T$params->{start_time}"
);
$errors = merge(
$self->check_time_limit($c, $start),
$self->check_conflicts($c, $start, $params->{end}),
);
}
unless ($errors) {
$object->insert({data => $params});
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
$_ = join ', ', @$_ foreach values %$errors;
}
else {
$object->init_defaults;
}
$c->stash->{reservation} = 1;
$c->stash->{reserve} = 1;
my $content = $c->view('Petal')->render_template(
$c,
{
user => $c->user->get('name'),
%{ $c->stash },
%$params,
template => 'custom/reservation/reserve.zpt',
uri_cancel => $c->stash->{context}->uri . '/cancel',
errors => $errors,
},
);
$c->stash({
template => 'index.zpt',
content => $content,
});
return;
}
=head3 check_time_limit($c, $start)
=cut
sub check_time_limit {
my ($self, $c, $start) = @_;
my $time_limit = $c->stash->{context}->property('reservation_time_limit', undef);
return unless $time_limit;
my $limit = DateTime->now(time_zone => 'local')
->set_time_zone('floating')
->add(hours => $time_limit);
return {start => ['too close']} if $start->datetime lt $limit->datetime;
return;
}
=head3 check_conflicts($c, $start)
=cut
sub check_conflicts {
my ($self, $c, $start, $end) = @_;
- my $reservations = $c->stash->{context}->property('reservations');
+ my $reservations = $c->stash->{context}->attribute('reservations');
my $new = create_datetime_span($start, $end);
- foreach my $existing (@$reservations) {
+ foreach my $existing (@{ $reservations->filtered(cancelled_by => undef) }) {
my $existing = create_datetime_span(
$existing->attribute('start')->object,
$existing->property('end')
);
if ($new->intersects($existing)) {
return {start => ['conflicting existent reservation']};
}
}
return;
}
=head4 create_datetime_span($start, $end)
=cut
sub create_datetime_span {
my ($start, $end) = @_;
my ($end_h, $end_m) = split /:/, $end;
return DateTime::Span->from_datetimes(
start => $start,
end => $start->clone->set_hour($end_h)->set_minute($end_m)->subtract(seconds => 1)
);
}
=head2 cancel
Cancel the given reservation.
=cut
sub cancel : CiderCMS('cancel') Args(1) {
my ($self, $c, $id) = @_;
my $context = $c->stash->{context};
my $reservation = $c->model('DB')->get_object($c, $id, $context->{level} + 1);
if ($reservation->{parent} == $context->{id}) {
$reservation->set_property(cancelled_by => $c->user->get('name'));
$reservation->update;
}
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
1;
diff --git a/t/custom_reservation.t b/t/custom_reservation.t
index caff3c4..f207cef 100644
--- a/t/custom_reservation.t
+++ b/t/custom_reservation.t
@@ -1,264 +1,282 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
repetitive => 1,
},
],
},
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'name',
data_type => 'String',
},
],
},
reservation => {
name => 'Reservation',
page_element => 1,
attributes => [
{
id => 'start',
data_type => 'DateTime',
mandatory => 1,
},
{
id => 'end',
data_type => 'Time',
mandatory => 1,
},
{
id => 'user',
data_type => 'String',
},
{
id => 'info',
data_type => 'String',
},
{
id => 'cancelled_by',
data_type => 'String',
},
],
},
airplane => {
name => 'Airplane',
page_element => 1,
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'reservations',
data_type => 'Object',
repetitive => 1,
},
{
id => 'reservation_time_limit',
data_type => 'Integer',
},
],
template => 'airplane.zpt'
},
});
my $root = $model->get_object($c, 1);
my $users = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Users' },
);
$users->create_child(
attribute => 'children',
type => 'user',
data => {
username => 'test',
name => 'test',
password => 'test',
},
);
my $airplanes = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Airplanes' },
);
my $dimona = $airplanes->create_child(
attribute => 'children',
type => 'airplane',
data => {
title => 'Dimona',
},
);
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->content_contains('Keine Reservierungen eingetragen.');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
$mech->content_lacks('Keine Reservierungen eingetragen.');
ok($mech->find_xpath(qq{//td[span="Heute"]}), "Today's reservation listed");
ok($mech->find_xpath(qq{//td[text()="test"]}), 'reserving user listed');
ok($mech->find_xpath(qq{//td[text()="Testflug"]}), 'Info listed');
$date->add(days => 1);
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
ok($mech->find_xpath(q{//td[span="Heute"]}), "Today's reservation still listed");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
$mech->get_ok(
$mech->find_xpath(q{//tr[td="Heute"]/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
is('' . $mech->find_xpath(q{//td[text()="Heute"]}), '', "Today's reservation gone");
ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/6/manage");
is($mech->value('cancelled_by'), 'test');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "conflicting existent reservation"]'),
'error message for conflict with existent reservation found'
);
+ $mech->get_ok(
+ $mech->find_xpath(q{//tr/td/a[@class="cancel"]/@href}),
+ 'cancel reservation'
+ );
+ $mech->submit_form_ok({
+ with_fields => {
+ start_date => $date->ymd,
+ start_time => $date->clone->add(hours => 2)->hour . ':00',
+ end => $date->clone->add(hours => 3)->hour . ':30',
+ info => 'Testflug2',
+ },
+ button => 'save',
+ });
+ ok(
+ not($mech->find_xpath('//span[text() = "conflicting existent reservation"]')),
+ 'error message for conflict with existent reservation not found anymore'
+ );
+
$model->dbh->rollback;
});
$model->txn_do(sub {
# test error handling
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => 'invalid',
start_time => 'nonsense',
end => 'forget',
info => '',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
$model->dbh->rollback;
});
$model->txn_do(sub {
# Update to test advance time limit
$dimona->set_property(reservation_time_limit => 24);
$dimona->update;
my $now = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->clone->add(hours => 1)->hms,
end => $now->clone->add(hours => 2)->hms,
info => 'too close',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "too close"]'), 'error message for too close date found');
$now = DateTime->now->add(days => 2)->add(hours => 4);
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->hms,
end => $now->clone->add(hours => 1)->hms,
info => 'too close',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too close"]'),
'',
'error message for too close date gone'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
ok($mech->find_xpath(qq{//p[text()="Frei"]}), "No reservation active for now");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->subtract(hours => 1)->hms(':'),
end => $date->clone->add(hours => 2)->hour . ':00',
info => 'Testflug',
},
button => 'save',
});
is('' . $mech->find_xpath(qq{//p[text()="Frei"]}), '', "Reservation active for now");
$model->dbh->rollback;
});
done_testing;
|
niner/CiderCMS
|
513911ab2fa1b37048af024007a201faba559ae1
|
Placeholders for usability
|
diff --git a/root/templates/custom/reservation/reserve.zpt b/root/templates/custom/reservation/reserve.zpt
index 0a41700..733809f 100644
--- a/root/templates/custom/reservation/reserve.zpt
+++ b/root/templates/custom/reservation/reserve.zpt
@@ -1,40 +1,40 @@
<div
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
>
<div tal:replace="structure context/render"/>
<form action="#reservations" name="new_reservation" class="new_reservation" method="post">
<fieldset>
<legend>Neue Reservierung eintragen</legend>
<label class="required date">
<span>Datum <span class="errors" tal:condition="true: errors/start" tal:content="errors/start"/></span>
<input type="date" name="start_date" tal:attributes="value start_date"/>
<script type="text/javascript" tal:attributes="src string:${uri_sys_static}/js/calendar.js" />
<script type="text/javascript" tal:content="string:A_TCALDEF['imgpath'] = '${uri_sys_static}/images/calendar/'" />
<script type="text/javascript">
new tcal ({'formname': 'new_reservation', 'controlname': 'start_date'});
</script>
</label>
<label class="start">
<span>Von </span>
- <input type="time" name="start_time" tal:attributes="value start_time"/>
+ <input type="time" name="start_time" tal:attributes="value start_time" placeholder="14:00"/>
</label>
<label class="end">
<span>Bis <span class="errors" tal:condition="true: errors/end" tal:content="errors/end"/></span>
- <input type="time" name="end" tal:attributes="value end"/>
+ <input type="time" name="end" tal:attributes="value end" placeholder="16:00"/>
</label>
<label class="user">
<span>Pilot <span class="errors" tal:condition="true: errors/user" tal:content="errors/user"/></span>
<input type="text" name="user" tal:attributes="value user"/>
</label>
<label class="info">
<span>Info <span class="errors" tal:condition="true: errors/info" tal:content="errors/info"/></span>
<textarea name="info" tal:content="info"/>
</label>
<button type="submit" name="save" value="1">Reservieren</button>
</fieldset>
</form>
</div>
|
niner/CiderCMS
|
8821ecc7d04b21af3741f5ccb3b0bbf83f56d4bd
|
Make new reservation link better stylable by adding a class
|
diff --git a/root/templates/custom/reservation/reservations.zpt b/root/templates/custom/reservation/reservations.zpt
index e9ef64b..fd6e523 100644
--- a/root/templates/custom/reservation/reservations.zpt
+++ b/root/templates/custom/reservation/reservations.zpt
@@ -1,48 +1,48 @@
<div
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
metal:define-macro="list"
tal:define="
reservations_attr context/attribute --reservations;
reservations_search reservations_attr/search --cancelled_by undef --start 'future';
reservations_sorted reservations_search/sort --start --end;
reservations reservations_sorted/list;
active_reservation_search reservations_attr/search --cancelled_by undef --start 'past' --start 'today' --end 'future';
active_reservation active_reservation_search/list
">
<p tal:condition="false: active_reservation" class="no_active_reservation">Frei</p>
<p tal:condition="false: reservations" class="no_reservations" id="reservations">
Keine Reservierungen eingetragen.
</p>
<table tal:condition="true: reservations" class="reservations" id="reservations">
<thead>
<tr>
<th>Datum</th>
<th>Von</th>
<th>Bis</th>
<th>Pilot</th>
</tr>
</thead>
<tbody tal:repeat="reservation reservations">
<tr tal:define="start reservation/attribute --start">
<td class="start_date" tal:attributes="data-date start/ymd">
<span tal:condition="false: start/is_today" tal:content="start/ymd"/>
<span tal:condition="true: start/is_today">Heute</span>
</td>
<td class="start_time" tal:content="start/format '%H:%M'"/>
<td class="end_time" tal:define="end reservation/attribute --end" tal:content="end/format '%H:%M'"/>
<td class="user" tal:content="reservation/property --user"/>
<td>
<a class="cancel" tal:attributes="href string:${context/uri}/cancel/${reservation/id}" onclick="return confirm('Reservierung stornieren?');">stornieren</a>
</td>
</tr>
<tr tal:condition="true: reservation/property --info">
<td class="info" colspan="5" tal:content="reservation/property --info"/>
</tr>
</tbody>
</table>
- <a tal:condition="false:reservation" tal:attributes="href string:${self/uri}/reserve">Neue Reservierung</a>
+ <a class="new_reservation" tal:condition="false:reservation" tal:attributes="href string:${self/uri}/reserve">Neue Reservierung</a>
</div>
|
niner/CiderCMS
|
ad8721e4beb67984717d944ce4274dbf79678298
|
croak instead of die for better error diagnosis
|
diff --git a/lib/CiderCMS/Object.pm b/lib/CiderCMS/Object.pm
index e4fdd92..5be5ac7 100644
--- a/lib/CiderCMS/Object.pm
+++ b/lib/CiderCMS/Object.pm
@@ -1,570 +1,570 @@
package CiderCMS::Object;
use strict;
use warnings;
use Scalar::Util qw(weaken);
use List::MoreUtils qw(any);
use File::Path qw(mkpath);
use File::Copy qw(move);
use Carp qw(croak);
use CiderCMS::Attribute;
=head1 NAME
CiderCMS::Object - Content objects
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
This class is the base for all content objects and provides the public API that can be used in templates.
=head1 METHODS
=head2 new({c => $c, id => 2, type => 'type1', parent => 1, parent_attr => 'children', sort_id => 0, data => {}})
=cut
sub new {
my ($class, $params) = @_;
$class = ref $class if ref $class;
my $c = $params->{c};
my $stash = $c->stash;
my $type = $params->{type};
my $data = $params->{data};
my $self = bless {
c => $params->{c},
id => $params->{id},
parent => $params->{parent},
parent_attr => $params->{parent_attr},
level => $params->{level},
type => $type,
sort_id => $params->{sort_id} || 0,
dcid => $params->{dcid},
attr => $stash->{types}{$type}{attr},
attributes => $stash->{types}{$type}{attributes},
}, $class;
weaken($self->{c});
foreach my $attr (@{ $self->{attributes} }) {
my $id = $attr->{id};
$self->{data}{$id} = $attr->{class}->new({c => $c, object => $self, data => $data->{$id}, %$attr});
}
return $self;
}
=head2 object_by_id($id)
Returns an object for the given ID
=cut
sub object_by_id {
my ($self, $id) = @_;
return $self->{c}->model('DB')->get_object($self->{c}, $id);
}
=head2 type
Returns the type info for this object.
For example:
{
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
=cut
sub type {
my ($self) = @_;
return $self->{c}->stash->{types}{$self->{type}};
}
=head2 property($property)
Returns the data of the named attribute
=cut
sub property {
my ($self, $property, $default) = @_;
unless (exists $self->{data}{$property}) {
return $default if @_ == 3;
- die "unknown property $property";
+ croak "unknown property $property";
}
return $self->{data}{$property}->data;
}
=head2 set_property($property, $data)
Sets the named attribute to the given value
=cut
sub set_property {
my ($self, $property, $data) = @_;
return $self->{data}{$property}->set_data($data);
}
=head2 attribute($attribute)
Returns the CiderCMS::Attribute object for the named attribute
=cut
sub attribute {
my ($self, $attribute) = @_;
return unless exists $self->{data}{$attribute};
return $self->{data}{$attribute};
}
=head2 update_data($data)
Updates this object's data from a hashref.
=cut
sub update_data {
my ($self, $data) = @_;
foreach (values %{ $self->{data} }) {
$_->set_data_from_form($data);
}
return;
}
=head2 init_defaults()
Initialize this object's data to the attributes' default values.
=cut
sub init_defaults {
my ($self) = @_;
$_->init_default foreach values %{ $self->{data} };
return;
}
=head2 parent
Returns the parent of this object, if any.
=cut
sub parent {
my ($self) = @_;
return unless $self->{parent};
return $self->{c}->model('DB')->get_object($self->{c}, $self->{parent}, $self->{level} - 1);
}
=head2 parent_by_level($level)
Returns the parent at a certain level.
The site object is at level 0.
=cut
sub parent_by_level {
my ($self, $level) = @_;
return if $self->{level} < $level; # already on a lower level
my $parent = $self;
while ($parent) {
return $parent if $parent->{level} == $level;
$parent = $parent->parent;
}
return;
}
=head2 children()
Returns the children of this object regardless to which attribute they belong.
Usually one should use $object->property('my_attribute') to only get the children of a certain attribute.
Returns a list in list context and an array ref in scalar context.
=cut
sub children {
my ($self) = @_;
return $self->{c}->model('DB')->object_children($self->{c}, $self);
}
=head2 uri()
Returns an URI without a file name for this object
=cut
sub uri {
my ($self) = @_;
my $parent = $self->parent;
my $dcid = ($self->{dcid} // $self->{id});
return ( ($parent ? $parent->uri : $self->{c}->uri_for_instance()) . ($dcid ? "/$dcid" : '') );
}
=head2 uri_index()
Returns an URI to the first object in this subtree that contains page elements.
If none does, return the URI to the first child.
=cut
sub uri_index {
my ($self) = @_;
my @children = $self->children;
if (not @children or any { $_->type->{page_element} } @children) { # we contain no children at all or page elements
return $self->uri . '/index.html';
}
else {
return $children[0]->uri_index;
}
}
=head2 uri_management()
Returns an URI to the management interface for this object
=cut
sub uri_management {
my ($self) = @_;
return $self->uri . '/manage';
}
=head2 uri_static()
Returns an URI for static file for this object
=cut
sub uri_static {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->uri_static : $self->{c}->uri_static_for_instance()) . "/$self->{id}" );
}
=head2 fs_path()
Returns the file system path to this node
=cut
sub fs_path {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->fs_path : $self->{c}->fs_path_for_instance()) . "/$self->{id}" );
}
=head2 edit_form($errors)
Renders the form for editing this object.
The optional $errors may be a hash reference with error messages for attributes.
=cut
sub edit_form {
my ($self, $errors) = @_;
$errors //= {};
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => 'edit.zpt',
self => $self,
attributes => [
map {
$self->{data}{$_->{id}}->input_field($errors->{$_->{id}})
} @{ $self->{attributes} },
],
});
}
=head2 render()
Returns an HTML representation of this object.
=cut
sub render {
my ($self) = @_;
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => "types/$self->{type}.zpt",
self => $self,
});
}
=head2 validate($data)
Validate the given data.
Returns a hash containing messages for violated constraints:
{
attr1 => ['missing'],
attr2 => ['invalid', 'wrong'],
}
=cut
sub validate {
my ($self, $data) = @_;
my %results;
foreach (values %{ $self->{data} }) {
my @result = $_->validate($data);
$results{ $_->{id} } = \@result if @result;
}
return \%results if keys %results;
return;
}
=head2 prepare_attributes()
Prepares attributes for insert and update operations.
=cut
sub prepare_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->prepare_update();
}
return;
}
=head2 update_attributes()
Runs update operation on attributes after inserts and updates.
=cut
sub update_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->post_update();
}
return;
}
=head2 insert({after => $after})
Inserts the object into the database.
=cut
sub insert {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data(delete $params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->insert_object($self->{c}, $self, $params);
$self->update_attributes;
return $result;
}
=head2 update()
Updates the object in the database.
=cut
sub update {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data($params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->update_object($self->{c}, $self);
$self->update_attributes;
return $result;
}
=head2 delete_from_db()
Deletes the object and it's children.
=cut
sub delete_from_db {
my ($self) = @_;
foreach ($self->children) {
$_->delete_from_db;
}
return $self->{c}->model('DB')->delete_object($self->{c}, $self);
}
=head2 get_dirty_columns()
Returns two array refs with column names and corresponding values.
=cut
sub get_dirty_columns {
my ($self) = @_;
my (@columns, @values);
foreach (@{ $self->{attributes} }) {
my $id = $_->{id};
my $attr = $self->{data}{$id};
if ($attr->db_type) {
push @columns, $id;
push @values, $attr->{data}; #TODO introduce an $attr->raw_data
}
}
return \@columns, \@values;
}
=head2 move_to(parent => $parent, parent_attr => $parent_attr, after => $after)
Moves this object (and it's subtree) to a new parent and or sort position
=cut
sub move_to {
my ($self, %params) = @_;
my $old_fs_path = $self->fs_path;
my $result = $self->{c}->model('DB')->move_object($self->{c}, $self, \%params);
if (-e $old_fs_path) {
my $new_fs_path = $self->fs_path;
mkpath $self->parent->fs_path if $self->{parent};
move $old_fs_path, $new_fs_path;
}
return $result;
}
=head2 new_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in memory for the given attribute.
=cut
sub new_child {
my ($self, %params) = @_;
$params{c} = $self->{c};
$params{parent} = $self->{id};
$params{level} = $self->{level};
$params{parent_attr} = delete $params{attribute};
croak "Invalid attribute: $params{parent_attr}"
unless exists $self->{data}{ $params{parent_attr} };
return CiderCMS::Object->new(\%params);
}
=head2 create_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in the database for the given attribute.
=cut
sub create_child {
my ($self, %params) = @_;
# Don't give data to new_child. Instead give it to insert so it gets treated like
# data subitted through the management UI.
my $data = delete $params{data};
my $child = $self->new_child(%params);
$child->insert({data => $data});
return $child;
}
=head2 user_has_access
Returns whether the currently logged in user has access to this folder and all
parent folders.
=cut
sub user_has_access {
my ($self) = @_;
return (not $self->property('restricted', 0) or $self->{c}->user);
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
|
niner/CiderCMS
|
5037c0175049711f17820716d8a98eae32908a8c
|
Another stash variable for templates to tailor output
|
diff --git a/lib/CiderCMS/Controller/Custom/Reservation.pm b/lib/CiderCMS/Controller/Custom/Reservation.pm
index 7cb9828..b6afcdf 100644
--- a/lib/CiderCMS/Controller/Custom/Reservation.pm
+++ b/lib/CiderCMS/Controller/Custom/Reservation.pm
@@ -1,152 +1,153 @@
package CiderCMS::Controller::Custom::Reservation;
use strict;
use warnings;
use parent 'Catalyst::Controller';
use DateTime::Format::ISO8601;
use DateTime::Span;
use Hash::Merge qw(merge);
=head2 reserve
Reserve the displayed plane.
=cut
sub reserve : CiderCMS('reserve') {
my ( $self, $c ) = @_;
$c->detach('/user/login') unless $c->user;
my $params = $c->req->params;
my $save = delete $params->{save};
my $object = $c->stash->{context}->new_child(
attribute => 'reservations',
type => 'reservation',
);
my $errors = {};
if ($save) {
$errors = $object->validate($params);
unless ($errors) {
$params->{start_time} = sprintf '%02i:%02i', split /:/, $params->{start_time};
my $start = DateTime::Format::ISO8601->new(
base_datetime => DateTime->now(time_zone => 'floating'),
)->parse_datetime(
"$params->{start_date}T$params->{start_time}"
);
$errors = merge(
$self->check_time_limit($c, $start),
$self->check_conflicts($c, $start, $params->{end}),
);
}
unless ($errors) {
$object->insert({data => $params});
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
$_ = join ', ', @$_ foreach values %$errors;
}
else {
$object->init_defaults;
}
$c->stash->{reservation} = 1;
+ $c->stash->{reserve} = 1;
my $content = $c->view('Petal')->render_template(
$c,
{
user => $c->user->get('name'),
%{ $c->stash },
%$params,
template => 'custom/reservation/reserve.zpt',
uri_cancel => $c->stash->{context}->uri . '/cancel',
errors => $errors,
},
);
$c->stash({
template => 'index.zpt',
content => $content,
});
return;
}
=head3 check_time_limit($c, $start)
=cut
sub check_time_limit {
my ($self, $c, $start) = @_;
my $time_limit = $c->stash->{context}->property('reservation_time_limit', undef);
return unless $time_limit;
my $limit = DateTime->now(time_zone => 'local')
->set_time_zone('floating')
->add(hours => $time_limit);
return {start => ['too close']} if $start->datetime lt $limit->datetime;
return;
}
=head3 check_conflicts($c, $start)
=cut
sub check_conflicts {
my ($self, $c, $start, $end) = @_;
my $reservations = $c->stash->{context}->property('reservations');
my $new = create_datetime_span($start, $end);
foreach my $existing (@$reservations) {
my $existing = create_datetime_span(
$existing->attribute('start')->object,
$existing->property('end')
);
if ($new->intersects($existing)) {
return {start => ['conflicting existent reservation']};
}
}
return;
}
=head4 create_datetime_span($start, $end)
=cut
sub create_datetime_span {
my ($start, $end) = @_;
my ($end_h, $end_m) = split /:/, $end;
return DateTime::Span->from_datetimes(
start => $start,
end => $start->clone->set_hour($end_h)->set_minute($end_m)->subtract(seconds => 1)
);
}
=head2 cancel
Cancel the given reservation.
=cut
sub cancel : CiderCMS('cancel') Args(1) {
my ($self, $c, $id) = @_;
my $context = $c->stash->{context};
my $reservation = $c->model('DB')->get_object($c, $id, $context->{level} + 1);
if ($reservation->{parent} == $context->{id}) {
$reservation->set_property(cancelled_by => $c->user->get('name'));
$reservation->update;
}
return $c->res->redirect($c->stash->{context}->uri . '/reserve');
}
1;
|
niner/CiderCMS
|
1f067fafc77a901e313a6e8170abe773737609c1
|
Javascript confirm for cancelling reservations
|
diff --git a/root/templates/custom/reservation/reservations.zpt b/root/templates/custom/reservation/reservations.zpt
index 629d715..e9ef64b 100644
--- a/root/templates/custom/reservation/reservations.zpt
+++ b/root/templates/custom/reservation/reservations.zpt
@@ -1,48 +1,48 @@
<div
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
metal:define-macro="list"
tal:define="
reservations_attr context/attribute --reservations;
reservations_search reservations_attr/search --cancelled_by undef --start 'future';
reservations_sorted reservations_search/sort --start --end;
reservations reservations_sorted/list;
active_reservation_search reservations_attr/search --cancelled_by undef --start 'past' --start 'today' --end 'future';
active_reservation active_reservation_search/list
">
<p tal:condition="false: active_reservation" class="no_active_reservation">Frei</p>
<p tal:condition="false: reservations" class="no_reservations" id="reservations">
Keine Reservierungen eingetragen.
</p>
<table tal:condition="true: reservations" class="reservations" id="reservations">
<thead>
<tr>
<th>Datum</th>
<th>Von</th>
<th>Bis</th>
<th>Pilot</th>
</tr>
</thead>
<tbody tal:repeat="reservation reservations">
<tr tal:define="start reservation/attribute --start">
<td class="start_date" tal:attributes="data-date start/ymd">
<span tal:condition="false: start/is_today" tal:content="start/ymd"/>
<span tal:condition="true: start/is_today">Heute</span>
</td>
<td class="start_time" tal:content="start/format '%H:%M'"/>
<td class="end_time" tal:define="end reservation/attribute --end" tal:content="end/format '%H:%M'"/>
<td class="user" tal:content="reservation/property --user"/>
<td>
- <a class="cancel" tal:attributes="href string:${context/uri}/cancel/${reservation/id}">stornieren</a>
+ <a class="cancel" tal:attributes="href string:${context/uri}/cancel/${reservation/id}" onclick="return confirm('Reservierung stornieren?');">stornieren</a>
</td>
</tr>
<tr tal:condition="true: reservation/property --info">
<td class="info" colspan="5" tal:content="reservation/property --info"/>
</tr>
</tbody>
</table>
<a tal:condition="false:reservation" tal:attributes="href string:${self/uri}/reserve">Neue Reservierung</a>
</div>
|
niner/CiderCMS
|
8e2e4982d0cde81bb66ffe752d93af487cd2cf9f
|
Implement validation of Integer attributes
|
diff --git a/lib/CiderCMS/Attribute/Integer.pm b/lib/CiderCMS/Attribute/Integer.pm
index 8432896..a671821 100644
--- a/lib/CiderCMS/Attribute/Integer.pm
+++ b/lib/CiderCMS/Attribute/Integer.pm
@@ -1,54 +1,69 @@
package CiderCMS::Attribute::Integer;
use strict;
use warnings;
use base qw(CiderCMS::Attribute);
=head1 NAME
CiderCMS::Attribute::Integer - Integer attribute
=head1 SYNOPSIS
See L<CiderCMS::Attribute>
=head1 DESCRIPTION
Simple integer attribute
=head1 METHODs
=head2 db_type
=cut
sub db_type {
return 'integer';
}
=head2 set_data($data)
Sets this attributes data to the given value.
=cut
sub set_data {
my ($self, $data) = @_;
return $self->{data} = $data if defined $data and $data ne '';
return $self->{data} = undef;
}
+=head2 validate
+
+Check if $data is a valid number.
+
+=cut
+
+sub validate {
+ my ($self, $data) = @_;
+
+ my $number = $data->{ $self->id };
+ return 'missing' if $self->{mandatory} and (not defined $number or $number eq '');
+ return 'invalid' if $number and $number =~ /\D/;
+ return;
+}
+
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/root/templates/attributes/integer.zpt b/root/templates/attributes/integer.zpt
index 0adee73..278d490 100644
--- a/root/templates/attributes/integer.zpt
+++ b/root/templates/attributes/integer.zpt
@@ -1,4 +1,5 @@
<label xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS">
<span tal:content="self/name"/>
+ <span class="errors" tal:condition="true: errors" tal:content="errors"/>
<input type="text" size="8" tal:attributes="name self/id; value self/data"/>
</label>
diff --git a/t/10Attribute-Integer.t b/t/10Attribute-Integer.t
index 506cca7..1c32706 100644
--- a/t/10Attribute-Integer.t
+++ b/t/10Attribute-Integer.t
@@ -1,38 +1,63 @@
use strict;
use warnings;
-use Test::More;
-use FindBin qw($Bin);
use utf8;
-eval "use Test::WWW::Mechanize::Catalyst 'CiderCMS'";
-plan $@
- ? ( skip_all => 'Test::WWW::Mechanize::Catalyst required' )
- : ( tests => 8 );
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
-ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
+CiderCMS::Test->populate_types({
+ tester => {
+ name => 'Tester',
+ attributes => [
+ {
+ id => 'number',
+ data_type => 'Integer',
+ mandatory => 1,
+ },
+ ],
+ page_element => 1,
+ template => 'integer_test.zpt',
+ },
+});
-$mech->get_ok( 'http://localhost/test.example/system/types' );
+$mech->get_ok("http://localhost/$instance/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=tester} }, 'Add a tester');
-$mech->follow_link_ok({ url_regex => qr{image/edit} }, 'Edit image type' );
$mech->submit_form_ok({
with_fields => {
- id => 'width',
- name => 'Image width',
- data_type => 'Integer',
+ number => '',
},
-}, 'Add width attribute');
+ button => 'save',
+});
-$mech->get_ok( 'http://localhost/test.example/manage' );
+$mech->content_contains('missing');
-# Try some image
-$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=image} }, 'Add an image');
$mech->submit_form_ok({
with_fields => {
- img => "$Bin/../root/static/images/catalyst_logo.png",
- width => 100,
- } ,
+ number => 'FooBar',
+ },
button => 'save',
});
-my $image = $mech->find_image(url_regex => qr{catalyst_logo});
-$mech->get_ok($image->url);
-$mech->back;
+
+$mech->content_contains('invalid');
+
+$mech->submit_form_ok({
+ with_fields => {
+ number => '0 or 1',
+ },
+ button => 'save',
+});
+
+$mech->content_contains('invalid');
+
+$mech->submit_form_ok({
+ with_fields => {
+ number => '0',
+ },
+ button => 'save',
+});
+
+$mech->get_ok("http://localhost/$instance/index.html");
+is('' . $mech->find_xpath('//div'), '0', 'Integer saved');
+
+done_testing;
diff --git a/t/test.example/templates/types/integer_test.zpt b/t/test.example/templates/types/integer_test.zpt
new file mode 100644
index 0000000..2e294c0
--- /dev/null
+++ b/t/test.example/templates/types/integer_test.zpt
@@ -0,0 +1,7 @@
+<div
+ xmlns:tal="http://purl.org/petal/1.0/"
+ xmlns:i18n="http://xml.zope.org/namespaces/i18n"
+ i18n:domain="CiderCMS"
+ tal:attributes="id string:object_${self/id}"
+ tal:content="self/property --number"
+/>
|
niner/CiderCMS
|
6ab30894b2a6dfada54fdafe6e1f28d1fbbc4589
|
Implement validation of Integer attributes
|
diff --git a/lib/CiderCMS/Attribute/Integer.pm b/lib/CiderCMS/Attribute/Integer.pm
index 8432896..a671821 100644
--- a/lib/CiderCMS/Attribute/Integer.pm
+++ b/lib/CiderCMS/Attribute/Integer.pm
@@ -1,54 +1,69 @@
package CiderCMS::Attribute::Integer;
use strict;
use warnings;
use base qw(CiderCMS::Attribute);
=head1 NAME
CiderCMS::Attribute::Integer - Integer attribute
=head1 SYNOPSIS
See L<CiderCMS::Attribute>
=head1 DESCRIPTION
Simple integer attribute
=head1 METHODs
=head2 db_type
=cut
sub db_type {
return 'integer';
}
=head2 set_data($data)
Sets this attributes data to the given value.
=cut
sub set_data {
my ($self, $data) = @_;
return $self->{data} = $data if defined $data and $data ne '';
return $self->{data} = undef;
}
+=head2 validate
+
+Check if $data is a valid number.
+
+=cut
+
+sub validate {
+ my ($self, $data) = @_;
+
+ my $number = $data->{ $self->id };
+ return 'missing' if $self->{mandatory} and (not defined $number or $number eq '');
+ return 'invalid' if $number and $number =~ /\D/;
+ return;
+}
+
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/root/templates/attributes/integer.zpt b/root/templates/attributes/integer.zpt
index 0adee73..278d490 100644
--- a/root/templates/attributes/integer.zpt
+++ b/root/templates/attributes/integer.zpt
@@ -1,4 +1,5 @@
<label xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS">
<span tal:content="self/name"/>
+ <span class="errors" tal:condition="true: errors" tal:content="errors"/>
<input type="text" size="8" tal:attributes="name self/id; value self/data"/>
</label>
diff --git a/t/10Attribute-Integer.t b/t/10Attribute-Integer.t
index 506cca7..1c32706 100644
--- a/t/10Attribute-Integer.t
+++ b/t/10Attribute-Integer.t
@@ -1,38 +1,63 @@
use strict;
use warnings;
-use Test::More;
-use FindBin qw($Bin);
use utf8;
-eval "use Test::WWW::Mechanize::Catalyst 'CiderCMS'";
-plan $@
- ? ( skip_all => 'Test::WWW::Mechanize::Catalyst required' )
- : ( tests => 8 );
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
-ok( my $mech = Test::WWW::Mechanize::Catalyst->new, 'Created mech object' );
+CiderCMS::Test->populate_types({
+ tester => {
+ name => 'Tester',
+ attributes => [
+ {
+ id => 'number',
+ data_type => 'Integer',
+ mandatory => 1,
+ },
+ ],
+ page_element => 1,
+ template => 'integer_test.zpt',
+ },
+});
-$mech->get_ok( 'http://localhost/test.example/system/types' );
+$mech->get_ok("http://localhost/$instance/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=tester} }, 'Add a tester');
-$mech->follow_link_ok({ url_regex => qr{image/edit} }, 'Edit image type' );
$mech->submit_form_ok({
with_fields => {
- id => 'width',
- name => 'Image width',
- data_type => 'Integer',
+ number => '',
},
-}, 'Add width attribute');
+ button => 'save',
+});
-$mech->get_ok( 'http://localhost/test.example/manage' );
+$mech->content_contains('missing');
-# Try some image
-$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=image} }, 'Add an image');
$mech->submit_form_ok({
with_fields => {
- img => "$Bin/../root/static/images/catalyst_logo.png",
- width => 100,
- } ,
+ number => 'FooBar',
+ },
button => 'save',
});
-my $image = $mech->find_image(url_regex => qr{catalyst_logo});
-$mech->get_ok($image->url);
-$mech->back;
+
+$mech->content_contains('invalid');
+
+$mech->submit_form_ok({
+ with_fields => {
+ number => '0 or 1',
+ },
+ button => 'save',
+});
+
+$mech->content_contains('invalid');
+
+$mech->submit_form_ok({
+ with_fields => {
+ number => '0',
+ },
+ button => 'save',
+});
+
+$mech->get_ok("http://localhost/$instance/index.html");
+is('' . $mech->find_xpath('//div'), '0', 'Integer saved');
+
+done_testing;
|
niner/CiderCMS
|
5533bf5ebfb9ec4171226b38080280e0aca6483e
|
Implement /system/logout
|
diff --git a/lib/CiderCMS/Controller/System.pm b/lib/CiderCMS/Controller/System.pm
index b41ea45..ffa630c 100644
--- a/lib/CiderCMS/Controller/System.pm
+++ b/lib/CiderCMS/Controller/System.pm
@@ -1,74 +1,89 @@
package CiderCMS::Controller::System;
use strict;
use warnings;
use parent 'Catalyst::Controller';
=head1 NAME
CiderCMS::Controller::System - Catalyst Controller
=head1 DESCRIPTION
Meta operations of the instance, e.g. everything not related to content manipulation.
=head1 METHODS
=head2 init
PathPart that sets up the current instance.
=cut
sub init : Chained('/') PathPart('') CaptureArgs(1) {
my ( $self, $c, $instance ) = @_;
$c->stash->{instance} = $instance;
my $model = $c->model('DB');
$model->initialize($c);
$c->stash({
uri_manage_types => $c->uri_for_instance('system/types'),
uri_manage_content => $model->get_object($c, 1)->uri_management,
});
return;
}
=head2 create
Create a new CiderCMS instance, e.g. a new website.
=cut
sub create :Local :Args(0) {
my ( $self, $c ) = @_;
my $valid = $c->form({
required => [qw(id title)],
});
if ($valid) {
$c->model('DB')->create_instance($c, scalar $valid->valid());
$c->stash({ instance => $valid->valid('id') });
return $c->res->redirect($c->uri_for_instance('manage'));
}
else {
$c->stash({ template => 'system/create.zpt' });
}
return;
}
+=head2 logout
+
+Ends the user's session
+
+=cut
+
+sub logout : Local :Args(0) {
+ my ( $self, $c ) = @_;
+
+ $c->logout;
+
+ return $c->res->redirect($c->req->referer) if $c->req->referer;
+ return $c->res->body('User logged out');
+}
+
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Controller/User.pm b/lib/CiderCMS/Controller/User.pm
index 3e69bf3..bd1614b 100644
--- a/lib/CiderCMS/Controller/User.pm
+++ b/lib/CiderCMS/Controller/User.pm
@@ -1,63 +1,68 @@
package CiderCMS::Controller::User;
use Moose;
use namespace::autoclean;
BEGIN {extends 'Catalyst::Controller'; }
=head1 NAME
CiderCMS::Controller::User - Catalyst Controller
=head1 DESCRIPTION
Catalyst Controller.
=head1 METHODS
=head2 login
Shows a login page.
=cut
sub login : Private {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $referer = delete $params->{referer};
if (%$params) {
if ($c->authenticate($params)) {
return $c->res->redirect($referer // $c->stash->{uri_raw});
}
else {
$c->stash({
%$params,
message => 'Invalid username/password',
});
}
}
$c->stash({
referer => $referer // $c->stash->{uri_raw},
template => 'login.zpt',
});
return;
}
+=head2 logout
+
+See L<CiderCMS::Controller::System::logout>
+
+=cut
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
__PACKAGE__->meta->make_immutable;
1;
diff --git a/t/16authorization.t b/t/16authorization.t
index 7fd4e87..5fa7794 100644
--- a/t/16authorization.t
+++ b/t/16authorization.t
@@ -1,169 +1,169 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
use FindBin qw($Bin);
$model->create_type($c, {id => 'folder', name => 'Folder', page_element => 0});
$model->create_attribute($c, {
type => 'folder',
id => 'title',
name => 'Title',
sort_id => 0,
data_type => 'Title',
repetitive => 0,
mandatory => 1,
default_value => '',
});
$model->create_attribute($c, {
type => 'folder',
id => 'restricted',
name => 'Restricted',
sort_id => 1,
data_type => 'Boolean',
repetitive => 0,
mandatory => 0,
default_value => 0,
});
$model->create_attribute($c, {
type => 'folder',
id => 'children',
name => 'Children',
sort_id => 1,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => 0,
});
$model->create_type($c, {id => 'user', name => 'User', page_element => 1});
$model->create_attribute($c, {
type => 'user',
id => 'username',
name => 'Name',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
});
$model->create_attribute($c, {
type => 'user',
id => 'password',
name => 'Password',
sort_id => 1,
data_type => 'Password',
repetitive => 0,
mandatory => 1,
default_value => '',
});
open my $template, '>', "$Bin/../root/instances/$instance/templates/types/user.zpt";
print $template q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>);
close $template;
$mech->get_ok("http://localhost/$instance/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Users',
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a folder');
$mech->submit_form_ok({
with_fields => {
title => 'Unrestricted',
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=folder} }, 'Add a restricted folder');
$mech->submit_form_ok({
with_fields => {
title => 'Restricted',
restricted => '1',
},
button => 'save',
});
$mech->get_ok("http://localhost/$instance/unrestricted/index.html");
$mech->content_lacks('Login');
# Try accessing restricted content
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
# Try logging in with a non-existing user
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->content_contains('Invalid username/password');
$mech->get_ok("http://localhost/$instance/users/manage");
$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=user} }, 'Add a user');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
button => 'save',
});
ok($mech->find_xpath('//div[text()="test"]'), 'new user listed');
# Try logging in with the wrong password
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'wrong',
},
});
$mech->content_contains('Invalid username/password');
# Now that the user exists, try to login again with correct credentials
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
$mech->content_lacks('Invalid username/password');
ok($mech->find_xpath('id("object_4")'), 'Login successful');
$mech->get_ok("http://localhost/$instance/users/manage");
$mech->follow_link_ok({text => 'User'});
$mech->submit_form_ok({
with_fields => {
password => 'test2',
},
button => 'save',
});
-$mech->cookie_jar({}); # Logout
+$mech->get_ok("http://localhost/system/logout");
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test2',
},
});
$mech->content_lacks('Invalid username/password');
ok($mech->find_xpath('id("object_4")'), 'Login successful');
done_testing;
|
niner/CiderCMS
|
0d9c047f6b842aa3b2f42f08c553719b1904ea9e
|
Implement Email attributes
|
diff --git a/lib/CiderCMS/Attribute/Email.pm b/lib/CiderCMS/Attribute/Email.pm
new file mode 100644
index 0000000..1c6036a
--- /dev/null
+++ b/lib/CiderCMS/Attribute/Email.pm
@@ -0,0 +1,50 @@
+package CiderCMS::Attribute::Email;
+
+use strict;
+use warnings;
+
+use base qw(CiderCMS::Attribute::String);
+
+use Regexp::Common qw(Email::Address);
+
+=head1 NAME
+
+CiderCMS::Attribute::Email - Email attribute
+
+=head1 SYNOPSIS
+
+See L<CiderCMS::Attribute>
+
+=head1 DESCRIPTION
+
+Simple attribute for Email addresses
+
+=head1 METHODs
+
+=head2 validate
+
+Check if email address looks valid.
+
+=cut
+
+sub validate {
+ my ($self, $data) = @_;
+
+ my $email = $data->{ $self->id };
+ return 'missing' if $self->{mandatory} and not $email;
+ return 'invalid' if $email and $email !~ /\A($RE{Email}{Address})\z/;
+ return;
+}
+
+=head1 AUTHOR
+
+Stefan Seifert
+
+=head1 LICENSE
+
+This library is free software, you can redistribute it and/or modify
+it under the same terms as Perl itself.
+
+=cut
+
+1;
diff --git a/root/templates/attributes/email.zpt b/root/templates/attributes/email.zpt
new file mode 100644
index 0000000..bde55e7
--- /dev/null
+++ b/root/templates/attributes/email.zpt
@@ -0,0 +1,5 @@
+<label xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS">
+ <span tal:content="self/name"/>
+ <span class="errors" tal:condition="true: errors" tal:content="errors"/>
+ <input type="text" size="60" tal:attributes="name self/id; value self/data"/>
+</label>
diff --git a/root/templates/attributes/string.zpt b/root/templates/attributes/string.zpt
index a713001..f684e3a 100644
--- a/root/templates/attributes/string.zpt
+++ b/root/templates/attributes/string.zpt
@@ -1,4 +1,5 @@
<label xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS">
<span tal:content="self/name"/>
+ <span class="errors" tal:condition="true: errors" tal:content="errors"/>
<input type="text" size="40" tal:attributes="name self/id; value self/data"/>
</label>
diff --git a/t/Attribute-Email.t b/t/Attribute-Email.t
new file mode 100644
index 0000000..550c5c1
--- /dev/null
+++ b/t/Attribute-Email.t
@@ -0,0 +1,62 @@
+use strict;
+use warnings;
+use utf8;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+
+CiderCMS::Test->populate_types({
+ tester => {
+ name => 'Tester',
+ attributes => [
+ {
+ id => 'email',
+ mandatory => 1,
+ },
+ ],
+ page_element => 1,
+ template => 'email_test.zpt',
+ },
+});
+
+$mech->get_ok("http://localhost/$instance/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=tester} }, 'Add a tester');
+
+$mech->submit_form_ok({
+ with_fields => {
+ email => "",
+ },
+ button => 'save',
+});
+
+$mech->content_contains('missing');
+
+$mech->submit_form_ok({
+ with_fields => {
+ email => "FooBar",
+ },
+ button => 'save',
+});
+
+$mech->content_contains('invalid');
+
+$mech->submit_form_ok({
+ with_fields => {
+ email => "FooBar@",
+ },
+ button => 'save',
+});
+
+$mech->content_contains('invalid');
+
+$mech->submit_form_ok({
+ with_fields => {
+ email => 'test@localhost',
+ },
+ button => 'save',
+});
+
+$mech->get_ok("http://localhost/$instance/index.html");
+is('' . $mech->find_xpath('//div'), 'test@localhost', 'Email saved');
+
+done_testing;
diff --git a/t/test.example/templates/types/email_test.zpt b/t/test.example/templates/types/email_test.zpt
new file mode 100644
index 0000000..6d39e0a
--- /dev/null
+++ b/t/test.example/templates/types/email_test.zpt
@@ -0,0 +1,7 @@
+<div
+ xmlns:tal="http://purl.org/petal/1.0/"
+ xmlns:i18n="http://xml.zope.org/namespaces/i18n"
+ i18n:domain="CiderCMS"
+ tal:attributes="id string:object_${self/id}"
+ tal:content="self/property --email"
+/>
|
niner/CiderCMS
|
d24b5b73b8378903f4e4b0eb85da2a1e779712e2
|
Check for missing mandatory fields in user registration
|
diff --git a/lib/CiderCMS/Attribute/String.pm b/lib/CiderCMS/Attribute/String.pm
index 0f83d68..ea9bf34 100644
--- a/lib/CiderCMS/Attribute/String.pm
+++ b/lib/CiderCMS/Attribute/String.pm
@@ -1,57 +1,70 @@
package CiderCMS::Attribute::String;
use strict;
use warnings;
use base qw(CiderCMS::Attribute);
=head1 NAME
CiderCMS::Attribute::String - String attribute
=head1 SYNOPSIS
See L<CiderCMS::Attribute>
=head1 DESCRIPTION
Simple string attribute
=head1 METHODs
=head2 db_type
=cut
sub db_type {
return 'varchar';
}
+=head2 validate
+
+Check if string is not empty.
+
+=cut
+
+sub validate {
+ my ($self, $data) = @_;
+
+ return 'missing' if $self->{mandatory} and not $data->{ $self->id };
+ return;
+}
+
=head2 filter_matches($value)
Returns true if this attribute matches the given filter value.
For now simply matches for equality.
=cut
sub filter_matches {
my ($self, $value) = @_;
return not defined $self->data unless defined $value;
return unless defined $self->data;
return $value eq $self->data;
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index 171c1fe..74fb38e 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,71 +1,72 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
use utf8;
use parent 'Catalyst::Controller';
use Email::Sender::Simple;
use Email::Stuffer;
use Encode qw(encode);
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
if ($errors) {
+ $_ = join ', ', @$_ foreach values %$errors;
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
$verify_uri->query_form({email => $params->{email}});
Email::Stuffer->from('noreply@' . $c->stash->{instance})
->to($params->{email})
->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
->text_body(
"Bitte klicken Sie auf den folgenden Link um die Anmeldung zu bestätigen:\n"
. $verify_uri
)
->send;
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
sub verify : CiderCMS('verify_registration') {
my ( $self, $c ) = @_;
my $users = $c->stash->{context}->attribute('children')->filtered(
email => $c->req->params->{email}
);
die "No user found for " . $c->req->params->{email} unless @$users;
my $user = $users->[0];
$user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
}
1;
diff --git a/t/custom_registration.t b/t/custom_registration.t
index a7c33a8..be393ac 100644
--- a/t/custom_registration.t
+++ b/t/custom_registration.t
@@ -1,245 +1,251 @@
use strict;
use warnings;
use utf8;
use Test::More;
BEGIN { $ENV{EMAIL_SENDER_TRANSPORT} = 'Test' }
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use FindBin qw($Bin);
use Regexp::Common qw(URI);
my ($root, $users, $restricted);
setup_test_instance();
test_registration_not_offered();
setup_registration_objects();
test_registration();
done_testing;
sub setup_test_instance {
setup_types();
setup_objects();
}
sub setup_types {
setup_folder_type();
setup_textarea_type();
setup_userlist_type();
setup_user_type();
setup_registration_type();
}
sub setup_folder_type {
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
template => 'folder.zpt',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'restricted',
data_type => 'Boolean',
default_value => 0,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_textarea_type {
CiderCMS::Test->populate_types({
textarea => {
name => 'Textarea',
template => 'textarea.zpt',
page_element => 1,
attributes => [
{
id => 'text',
mandatory => 1,
},
],
},
});
}
sub setup_userlist_type {
CiderCMS::Test->populate_types({
userlist => {
name => 'User list',
attributes => [{
type => 'userlist',
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_user_type {
CiderCMS::Test->populate_types({
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'email',
data_type => 'String',
mandatory => 1,
},
],
},
});
CiderCMS::Test->write_template('user', q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>));
}
sub setup_objects {
$root = $model->get_object($c, 1);
$users = $root->create_child(
attribute => 'children',
type => 'userlist',
data => { title => 'Users' },
);
$restricted = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Restricted', restricted => 1 },
);
}
sub setup_registration_type {
CiderCMS::Test->populate_types({
registration => {
name => 'Registration',
template => 'registration.zpt',
attributes => [
{
id => 'children',
data_type => 'Object',
},
{
id => 'success',
data_type => 'Object',
},
{
id => 'verified',
data_type => 'Object',
},
],
},
});
$model->create_attribute($c, {
type => 'userlist',
id => 'registration',
name => 'Registration',
sort_id => 0,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => '',
});
}
sub setup_registration_objects {
my $registration = $users->create_child(
attribute => 'registration',
type => 'registration',
data => {},
);
my $success = $registration->create_child(
attribute => 'success',
type => 'folder',
data => { title => 'Success' },
);
$success->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! Please check your email.' },
);
my $verified = $registration->create_child(
attribute => 'verified',
type => 'folder',
data => { title => 'Verified' },
);
$verified->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! You are now registered.' },
);
}
sub test_registration_not_offered {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_lacks('Neuen Benutzer registrieren');
}
sub test_registration {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_contains('Neuen Benutzer registrieren');
$mech->follow_link_ok({text => 'Neuen Benutzer registrieren'});
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
+ },
+ });
+ $mech->content_contains('missing');
+ $mech->submit_form_ok({
+ with_fields => {
+ password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
my @deliveries = Email::Sender::Simple->default_transport->deliveries;
is(scalar @deliveries, 1, 'Confirmation message sent');
my $envelope = $deliveries[0]->{envelope};
is_deeply($envelope->{to}, ['test@localhost'], 'Confirmation message recipient correct');
is($envelope->{from}, "noreply\@$instance", 'Confirmation message sender correct');
my $email = $deliveries[0]->{email};
is(
$email->get_header("Subject"),
"Bestätigung der Anmeldung zu $instance",
'Confirmation message subject correct'
);
my ($link) = $email->get_body =~ /($RE{URI}{HTTP})/;
$mech->get_ok($link);
$mech->content_lacks('Login');
$mech->content_contains('Success! You are now registered.');
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
$mech->content_lacks('Login');
$mech->content_lacks('Invalid username/password');
$mech->title_is('Restricted');
}
diff --git a/t/test.example/templates/types/registration.zpt b/t/test.example/templates/types/registration.zpt
index dd23d41..9879e02 100644
--- a/t/test.example/templates/types/registration.zpt
+++ b/t/test.example/templates/types/registration.zpt
@@ -1,24 +1,24 @@
<form
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:i18n="http://xml.zope.org/namespaces/i18n"
i18n:domain="CiderCMS"
tal:attributes="id string:object_${self/id}; action string:${context/uri}/register"
method="post"
>
<div tal:condition="true: c/req/params/username">
<span tal:replace=""/>
</div>
<label>
- <span>Benutzername:</span>
+ <span>Benutzername: <span class="errors" tal:condition="true: errors" tal:content="errors/username"/></span>
<input type="text" name="username" tal:attributes="value username"/>
</label>
<label>
- <span>Passwort:</span>
+ <span>Passwort: <span class="errors" tal:condition="true: errors" tal:content="errors/password"/></span>
<input type="password" name="password"/>
</label>
<label>
- <span>Email:</span>
+ <span>Email: <span class="errors" tal:condition="true: errors" tal:content="errors/email"/></span>
<input type="text" name="email" tal:attributes="value email"/>
</label>
<button type="submit">Registrieren</button>
</form>
|
niner/CiderCMS
|
c62b7622cdc39ae63260ea55dc53dd13ef5a904b
|
Don't copy root/static/instances to blib
|
diff --git a/Makefile.PL b/Makefile.PL
index 85c18d6..c0d5cb8 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,44 +1,45 @@
#!/usr/bin/env perl
# IMPORTANT: if you delete this file your app will not work as
# expected. You have been warned.
use inc::Module::Install;
name 'CiderCMS';
all_from 'lib/CiderCMS.pm';
requires 'Catalyst::Runtime' => '5.80011';
requires 'Catalyst::Plugin::ConfigLoader';
requires 'Catalyst::Plugin::Static::Simple';
requires 'Catalyst::Plugin::Unicode::Encoding';
requires 'Catalyst::Plugin::Session';
requires 'Catalyst::Plugin::Session::State::Cookie';
requires 'Catalyst::Plugin::Session::Store::FastMmap';
requires 'Catalyst::Action::RenderView';
requires 'parent';
requires 'Config::General'; # This should reflect the config file format you've chosen
# See Catalyst::Plugin::ConfigLoader for supported formats
requires 'Catalyst::Model::DBI';
requires 'Catalyst::View::Petal';
requires 'Petal::Utils';
requires 'Catalyst::Plugin::FormValidator';
requires 'DateTime';
requires 'DateTime::Format::ISO8601';
requires 'DateTime::Span';
requires 'Digest::SHA';
requires 'Module::Pluggable';
requires 'Image::Imlib2';
requires 'File::Path';
requires 'File::Copy';
requires 'File::Temp';
requires 'File::Find';
requires 'File::Slurp';
requires 'Cwd';
requires 'MIME::Lite';
requires 'Email::Sender::Simple';
requires 'Email::Stuffer';
requires 'Regexp::Common::URI';
+catalyst_ignore('root'); # avoid copying root/static/instances
catalyst;
install_script glob('script/*.pl');
auto_install;
WriteAll;
|
niner/CiderCMS
|
dca6018382e90ab654634cb4a8fc6fe441d73dc9
|
Implement email verification for user registration
|
diff --git a/Makefile.PL b/Makefile.PL
index cd61dde..85c18d6 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,41 +1,44 @@
#!/usr/bin/env perl
# IMPORTANT: if you delete this file your app will not work as
# expected. You have been warned.
use inc::Module::Install;
name 'CiderCMS';
all_from 'lib/CiderCMS.pm';
requires 'Catalyst::Runtime' => '5.80011';
requires 'Catalyst::Plugin::ConfigLoader';
requires 'Catalyst::Plugin::Static::Simple';
requires 'Catalyst::Plugin::Unicode::Encoding';
requires 'Catalyst::Plugin::Session';
requires 'Catalyst::Plugin::Session::State::Cookie';
requires 'Catalyst::Plugin::Session::Store::FastMmap';
requires 'Catalyst::Action::RenderView';
requires 'parent';
requires 'Config::General'; # This should reflect the config file format you've chosen
# See Catalyst::Plugin::ConfigLoader for supported formats
requires 'Catalyst::Model::DBI';
requires 'Catalyst::View::Petal';
requires 'Petal::Utils';
requires 'Catalyst::Plugin::FormValidator';
requires 'DateTime';
requires 'DateTime::Format::ISO8601';
requires 'DateTime::Span';
requires 'Digest::SHA';
requires 'Module::Pluggable';
requires 'Image::Imlib2';
requires 'File::Path';
requires 'File::Copy';
requires 'File::Temp';
requires 'File::Find';
requires 'File::Slurp';
requires 'Cwd';
requires 'MIME::Lite';
+requires 'Email::Sender::Simple';
+requires 'Email::Stuffer';
+requires 'Regexp::Common::URI';
catalyst;
install_script glob('script/*.pl');
auto_install;
WriteAll;
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
index 4c164cb..171c1fe 100644
--- a/lib/CiderCMS/Controller/Custom/Registration.pm
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -1,39 +1,71 @@
package CiderCMS::Controller::Custom::Registration;
use strict;
use warnings;
+use utf8;
use parent 'Catalyst::Controller';
+use Email::Sender::Simple;
+use Email::Stuffer;
+use Encode qw(encode);
+
=head2 register
Register a new user.
=cut
sub register : CiderCMS('register') {
my ( $self, $c ) = @_;
my $params = $c->req->params;
- my $object = $c->stash->{context}->parent->new_child(
+ my $object = $c->stash->{context}->new_child(
attribute => 'children',
type => 'user',
);
my $errors = $object->validate($params);
if ($errors) {
$c->stash({
%$params,
errors => $errors,
});
$c->forward('/content/index_html');
}
else {
$object->insert({data => $params});
+
+ my $verify_uri = URI->new($c->stash->{context}->uri . '/verify_registration');
+ $verify_uri->query_form({email => $params->{email}});
+
+ Email::Stuffer->from('noreply@' . $c->stash->{instance})
+ ->to($params->{email})
+ ->subject('Bestätigung der Anmeldung zu ' . $c->stash->{instance})
+ ->text_body(
+ "Bitte klicken Sie auf den folgenden Link um die Anmeldung zu bestätigen:\n"
+ . $verify_uri
+ )
+ ->send;
+
return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
}
return;
}
+sub verify : CiderCMS('verify_registration') {
+ my ( $self, $c ) = @_;
+
+ my $users = $c->stash->{context}->attribute('children')->filtered(
+ email => $c->req->params->{email}
+ );
+ die "No user found for " . $c->req->params->{email} unless @$users;
+
+ my $user = $users->[0];
+ $user->move_to(parent => $c->stash->{context}->parent, parent_attr => 'children');
+
+ return $c->res->redirect($c->stash->{context}->property('verified')->[0]->uri_index);
+}
+
1;
diff --git a/lib/CiderCMS/Object.pm b/lib/CiderCMS/Object.pm
index 6cc3d26..e4fdd92 100644
--- a/lib/CiderCMS/Object.pm
+++ b/lib/CiderCMS/Object.pm
@@ -1,570 +1,570 @@
package CiderCMS::Object;
use strict;
use warnings;
use Scalar::Util qw(weaken);
use List::MoreUtils qw(any);
use File::Path qw(mkpath);
use File::Copy qw(move);
use Carp qw(croak);
use CiderCMS::Attribute;
=head1 NAME
CiderCMS::Object - Content objects
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
This class is the base for all content objects and provides the public API that can be used in templates.
=head1 METHODS
=head2 new({c => $c, id => 2, type => 'type1', parent => 1, parent_attr => 'children', sort_id => 0, data => {}})
=cut
sub new {
my ($class, $params) = @_;
$class = ref $class if ref $class;
my $c = $params->{c};
my $stash = $c->stash;
my $type = $params->{type};
my $data = $params->{data};
my $self = bless {
c => $params->{c},
id => $params->{id},
parent => $params->{parent},
parent_attr => $params->{parent_attr},
level => $params->{level},
type => $type,
sort_id => $params->{sort_id} || 0,
dcid => $params->{dcid},
attr => $stash->{types}{$type}{attr},
attributes => $stash->{types}{$type}{attributes},
}, $class;
weaken($self->{c});
foreach my $attr (@{ $self->{attributes} }) {
my $id = $attr->{id};
$self->{data}{$id} = $attr->{class}->new({c => $c, object => $self, data => $data->{$id}, %$attr});
}
return $self;
}
=head2 object_by_id($id)
Returns an object for the given ID
=cut
sub object_by_id {
my ($self, $id) = @_;
return $self->{c}->model('DB')->get_object($self->{c}, $id);
}
=head2 type
Returns the type info for this object.
For example:
{
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
=cut
sub type {
my ($self) = @_;
return $self->{c}->stash->{types}{$self->{type}};
}
=head2 property($property)
Returns the data of the named attribute
=cut
sub property {
my ($self, $property, $default) = @_;
unless (exists $self->{data}{$property}) {
return $default if @_ == 3;
die "unknown property $property";
}
return $self->{data}{$property}->data;
}
=head2 set_property($property, $data)
Sets the named attribute to the given value
=cut
sub set_property {
my ($self, $property, $data) = @_;
return $self->{data}{$property}->set_data($data);
}
=head2 attribute($attribute)
Returns the CiderCMS::Attribute object for the named attribute
=cut
sub attribute {
my ($self, $attribute) = @_;
return unless exists $self->{data}{$attribute};
return $self->{data}{$attribute};
}
=head2 update_data($data)
Updates this object's data from a hashref.
=cut
sub update_data {
my ($self, $data) = @_;
foreach (values %{ $self->{data} }) {
$_->set_data_from_form($data);
}
return;
}
=head2 init_defaults()
Initialize this object's data to the attributes' default values.
=cut
sub init_defaults {
my ($self) = @_;
$_->init_default foreach values %{ $self->{data} };
return;
}
=head2 parent
Returns the parent of this object, if any.
=cut
sub parent {
my ($self) = @_;
return unless $self->{parent};
return $self->{c}->model('DB')->get_object($self->{c}, $self->{parent}, $self->{level} - 1);
}
=head2 parent_by_level($level)
Returns the parent at a certain level.
The site object is at level 0.
=cut
sub parent_by_level {
my ($self, $level) = @_;
return if $self->{level} < $level; # already on a lower level
my $parent = $self;
while ($parent) {
return $parent if $parent->{level} == $level;
$parent = $parent->parent;
}
return;
}
=head2 children()
Returns the children of this object regardless to which attribute they belong.
Usually one should use $object->property('my_attribute') to only get the children of a certain attribute.
Returns a list in list context and an array ref in scalar context.
=cut
sub children {
my ($self) = @_;
return $self->{c}->model('DB')->object_children($self->{c}, $self);
}
=head2 uri()
Returns an URI without a file name for this object
=cut
sub uri {
my ($self) = @_;
my $parent = $self->parent;
my $dcid = ($self->{dcid} // $self->{id});
return ( ($parent ? $parent->uri : $self->{c}->uri_for_instance()) . ($dcid ? "/$dcid" : '') );
}
=head2 uri_index()
Returns an URI to the first object in this subtree that contains page elements.
If none does, return the URI to the first child.
=cut
sub uri_index {
my ($self) = @_;
my @children = $self->children;
if (not @children or any { $_->type->{page_element} } @children) { # we contain no children at all or page elements
return $self->uri . '/index.html';
}
else {
return $children[0]->uri_index;
}
}
=head2 uri_management()
Returns an URI to the management interface for this object
=cut
sub uri_management {
my ($self) = @_;
return $self->uri . '/manage';
}
=head2 uri_static()
Returns an URI for static file for this object
=cut
sub uri_static {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->uri_static : $self->{c}->uri_static_for_instance()) . "/$self->{id}" );
}
=head2 fs_path()
Returns the file system path to this node
=cut
sub fs_path {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->fs_path : $self->{c}->fs_path_for_instance()) . "/$self->{id}" );
}
=head2 edit_form($errors)
Renders the form for editing this object.
The optional $errors may be a hash reference with error messages for attributes.
=cut
sub edit_form {
my ($self, $errors) = @_;
$errors //= {};
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => 'edit.zpt',
self => $self,
attributes => [
map {
$self->{data}{$_->{id}}->input_field($errors->{$_->{id}})
} @{ $self->{attributes} },
],
});
}
=head2 render()
Returns an HTML representation of this object.
=cut
sub render {
my ($self) = @_;
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => "types/$self->{type}.zpt",
self => $self,
});
}
=head2 validate($data)
Validate the given data.
Returns a hash containing messages for violated constraints:
{
attr1 => ['missing'],
attr2 => ['invalid', 'wrong'],
}
=cut
sub validate {
my ($self, $data) = @_;
my %results;
foreach (values %{ $self->{data} }) {
my @result = $_->validate($data);
$results{ $_->{id} } = \@result if @result;
}
return \%results if keys %results;
return;
}
=head2 prepare_attributes()
Prepares attributes for insert and update operations.
=cut
sub prepare_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->prepare_update();
}
return;
}
=head2 update_attributes()
Runs update operation on attributes after inserts and updates.
=cut
sub update_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->post_update();
}
return;
}
=head2 insert({after => $after})
Inserts the object into the database.
=cut
sub insert {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data(delete $params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->insert_object($self->{c}, $self, $params);
$self->update_attributes;
return $result;
}
=head2 update()
Updates the object in the database.
=cut
sub update {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data($params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->update_object($self->{c}, $self);
$self->update_attributes;
return $result;
}
=head2 delete_from_db()
Deletes the object and it's children.
=cut
sub delete_from_db {
my ($self) = @_;
foreach ($self->children) {
$_->delete_from_db;
}
return $self->{c}->model('DB')->delete_object($self->{c}, $self);
}
=head2 get_dirty_columns()
Returns two array refs with column names and corresponding values.
=cut
sub get_dirty_columns {
my ($self) = @_;
my (@columns, @values);
foreach (@{ $self->{attributes} }) {
my $id = $_->{id};
my $attr = $self->{data}{$id};
if ($attr->db_type) {
push @columns, $id;
push @values, $attr->{data}; #TODO introduce an $attr->raw_data
}
}
return \@columns, \@values;
}
-=head2 move_to(parent => $parent, after => $after)
+=head2 move_to(parent => $parent, parent_attr => $parent_attr, after => $after)
Moves this object (and it's subtree) to a new parent and or sort position
=cut
sub move_to {
my ($self, %params) = @_;
my $old_fs_path = $self->fs_path;
my $result = $self->{c}->model('DB')->move_object($self->{c}, $self, \%params);
if (-e $old_fs_path) {
my $new_fs_path = $self->fs_path;
mkpath $self->parent->fs_path if $self->{parent};
move $old_fs_path, $new_fs_path;
}
return $result;
}
=head2 new_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in memory for the given attribute.
=cut
sub new_child {
my ($self, %params) = @_;
$params{c} = $self->{c};
$params{parent} = $self->{id};
$params{level} = $self->{level};
$params{parent_attr} = delete $params{attribute};
croak "Invalid attribute: $params{parent_attr}"
unless exists $self->{data}{ $params{parent_attr} };
return CiderCMS::Object->new(\%params);
}
=head2 create_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in the database for the given attribute.
=cut
sub create_child {
my ($self, %params) = @_;
# Don't give data to new_child. Instead give it to insert so it gets treated like
# data subitted through the management UI.
my $data = delete $params{data};
my $child = $self->new_child(%params);
$child->insert({data => $data});
return $child;
}
=head2 user_has_access
Returns whether the currently logged in user has access to this folder and all
parent folders.
=cut
sub user_has_access {
my ($self) = @_;
return (not $self->property('restricted', 0) or $self->{c}->user);
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
diff --git a/root/templates/login.zpt b/root/templates/login.zpt
index 6194ea7..86f2e91 100644
--- a/root/templates/login.zpt
+++ b/root/templates/login.zpt
@@ -1,43 +1,43 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
xml:lang="en"
lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
xmlns:i18n="http://xml.zope.org/namespaces/i18n"
i18n:domain="CiderCMS">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title tal:content="context/property --title 'CiderCMS Login'">CiderCMS Login</title>
<link rel="stylesheet" tal:attributes="href string:${uri_sys_static}/css/management.css" />
</head>
<body>
<h1>CiderCMS Login</h1>
<form action="" method="post">
<input type="hidden" name="referer" tal:attributes="value referer"/>
<input type="hidden" name="parent" value="2"/>
<input type="hidden" name="parent_attr" value="children"/>
<p tal:condition="true: message" tal:content="message"/>
<label>
<span>User name:</span>
<input type="text" name="username" tal:attributes="value username"/>
</label>
<label>
<span>Password:</span>
<input type="password" name="password"/>
</label>
<button type="submit">Login</button>
</form>
<p
tal:define="users context/object_by_id '2'; registration users/property --registration undef"
tal:condition="true: registration"
class="registration">
- <a tal:attributes="href registration/0/uri_index">
+ <a tal:attributes="href string:${registration/0/uri}/index.html">
Neuen Benutzer registrieren
</a>
</p>
</body>
</html>
diff --git a/t/custom_registration.t b/t/custom_registration.t
index 31b513c..a7c33a8 100644
--- a/t/custom_registration.t
+++ b/t/custom_registration.t
@@ -1,213 +1,245 @@
use strict;
use warnings;
use utf8;
-use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
+BEGIN { $ENV{EMAIL_SENDER_TRANSPORT} = 'Test' }
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
use FindBin qw($Bin);
+use Regexp::Common qw(URI);
my ($root, $users, $restricted);
setup_test_instance();
test_registration_not_offered();
setup_registration_objects();
test_registration();
done_testing;
sub setup_test_instance {
setup_types();
setup_objects();
}
sub setup_types {
setup_folder_type();
setup_textarea_type();
setup_userlist_type();
setup_user_type();
setup_registration_type();
}
sub setup_folder_type {
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
template => 'folder.zpt',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'restricted',
data_type => 'Boolean',
default_value => 0,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_textarea_type {
CiderCMS::Test->populate_types({
textarea => {
name => 'Textarea',
template => 'textarea.zpt',
page_element => 1,
attributes => [
{
id => 'text',
mandatory => 1,
},
],
},
});
}
sub setup_userlist_type {
CiderCMS::Test->populate_types({
userlist => {
name => 'User list',
attributes => [{
type => 'userlist',
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_user_type {
CiderCMS::Test->populate_types({
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'email',
data_type => 'String',
mandatory => 1,
},
],
},
});
CiderCMS::Test->write_template('user', q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>));
}
sub setup_objects {
$root = $model->get_object($c, 1);
$users = $root->create_child(
attribute => 'children',
type => 'userlist',
data => { title => 'Users' },
);
$restricted = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Restricted', restricted => 1 },
);
}
sub setup_registration_type {
CiderCMS::Test->populate_types({
registration => {
name => 'Registration',
template => 'registration.zpt',
attributes => [
{
id => 'children',
data_type => 'Object',
},
{
id => 'success',
data_type => 'Object',
},
+ {
+ id => 'verified',
+ data_type => 'Object',
+ },
],
},
});
$model->create_attribute($c, {
type => 'userlist',
id => 'registration',
name => 'Registration',
sort_id => 0,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => '',
});
}
sub setup_registration_objects {
my $registration = $users->create_child(
attribute => 'registration',
type => 'registration',
data => {},
);
- $registration->create_child(
- attribute => 'children',
- type => 'textarea',
- data => { text => 'Test' },
- );
my $success = $registration->create_child(
attribute => 'success',
type => 'folder',
data => { title => 'Success' },
);
$success->create_child(
attribute => 'children',
type => 'textarea',
data => { text => 'Success! Please check your email.' },
);
+ my $verified = $registration->create_child(
+ attribute => 'verified',
+ type => 'folder',
+ data => { title => 'Verified' },
+ );
+ $verified->create_child(
+ attribute => 'children',
+ type => 'textarea',
+ data => { text => 'Success! You are now registered.' },
+ );
}
sub test_registration_not_offered {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_lacks('Neuen Benutzer registrieren');
}
sub test_registration {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_contains('Neuen Benutzer registrieren');
$mech->follow_link_ok({text => 'Neuen Benutzer registrieren'});
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
email => 'test@localhost',
},
});
$mech->content_contains('Success! Please check your email.');
+ my @deliveries = Email::Sender::Simple->default_transport->deliveries;
+ is(scalar @deliveries, 1, 'Confirmation message sent');
+ my $envelope = $deliveries[0]->{envelope};
+ is_deeply($envelope->{to}, ['test@localhost'], 'Confirmation message recipient correct');
+ is($envelope->{from}, "noreply\@$instance", 'Confirmation message sender correct');
+ my $email = $deliveries[0]->{email};
+ is(
+ $email->get_header("Subject"),
+ "Bestätigung der Anmeldung zu $instance",
+ 'Confirmation message subject correct'
+ );
+
+ my ($link) = $email->get_body =~ /($RE{URI}{HTTP})/;
+ $mech->get_ok($link);
+ $mech->content_lacks('Login');
+ $mech->content_contains('Success! You are now registered.');
+
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->submit_form_ok({
with_fields => {
username => 'testname',
password => 'testpass',
},
});
+ $mech->content_lacks('Login');
+ $mech->content_lacks('Invalid username/password');
+ $mech->title_is('Restricted');
}
|
niner/CiderCMS
|
f520988d64f938df366f76d41400fdff4adbe128
|
Implement simple registration of users
|
diff --git a/lib/CiderCMS/Controller/Custom/Registration.pm b/lib/CiderCMS/Controller/Custom/Registration.pm
new file mode 100644
index 0000000..4c164cb
--- /dev/null
+++ b/lib/CiderCMS/Controller/Custom/Registration.pm
@@ -0,0 +1,39 @@
+package CiderCMS::Controller::Custom::Registration;
+
+use strict;
+use warnings;
+use parent 'Catalyst::Controller';
+
+=head2 register
+
+Register a new user.
+
+=cut
+
+sub register : CiderCMS('register') {
+ my ( $self, $c ) = @_;
+
+ my $params = $c->req->params;
+ my $object = $c->stash->{context}->parent->new_child(
+ attribute => 'children',
+ type => 'user',
+ );
+
+ my $errors = $object->validate($params);
+ if ($errors) {
+ $c->stash({
+ %$params,
+ errors => $errors,
+ });
+ $c->forward('/content/index_html');
+ }
+ else {
+ $object->insert({data => $params});
+ return $c->res->redirect($c->stash->{context}->property('success')->[0]->uri_index);
+ }
+
+ return;
+}
+
+1;
+
diff --git a/lib/CiderCMS/Test.pm b/lib/CiderCMS/Test.pm
index 2c1737c..e9e409a 100644
--- a/lib/CiderCMS/Test.pm
+++ b/lib/CiderCMS/Test.pm
@@ -1,178 +1,185 @@
package CiderCMS::Test;
use strict;
use warnings;
use utf8;
use Test::More;
use Exporter;
use FindBin qw($Bin); ## no critic (ProhibitPackageVars)
use File::Copy qw(copy);
use File::Path qw(remove_tree);
+use File::Slurp qw(write_file);
use English '-no_match_vars';
use base qw(Exporter);
=head1 NAME
CiderCMS::Test - Infrastructure for test files
=head1 SYNOPSIS
use CiderCMS::Test qw(test_instance => 1, mechanize => 1);
=head1 DESCRIPTION
This module contains methods for simplifying writing of tests.
It supports creating a test instance on import and initializing $mech.
=head1 EXPORTS
=head2 $instance
The randomly created name of the test instance.
=head2 $c
A CiderCMS object for accessing the test instance.
=head2 $model
A CiderCMS::Model::DB object.
=head2 $mech
A Test::WWW::Mechanize::Catalyst object for conducting UI tests.
=cut
## no critic (ProhibitReusedNames)
our ($instance, $c, $model, $mech); ## no critic (ProhibitPackageVars)
our @EXPORT = qw($instance $c $model $mech); ## no critic (ProhibitPackageVars, ProhibitAutomaticExportation)
sub import {
my ($self, %params) = @_;
if ($params{test_instance}) {
($instance, $c, $model, $mech) = $self->setup_test_environment(%params);
__PACKAGE__->export_to_level(1, $self, @EXPORT);
}
return;
}
=head1 METHODS
=head2 init_mechanize()
=cut
sub init_mechanize {
my ($self) = @_;
my $result = eval q{use Test::WWW::Mechanize::Catalyst 'CiderCMS'}; ## no critic (ProhibitStringyEval)
plan skip_all => "Test::WWW::Mechanize::Catalyst required: $EVAL_ERROR"
if $EVAL_ERROR;
require WWW::Mechanize::TreeBuilder;
require HTML::TreeBuilder::XPath;
my $mech = Test::WWW::Mechanize::Catalyst->new;
WWW::Mechanize::TreeBuilder->meta->apply(
$mech,
tree_class => 'HTML::TreeBuilder::XPath',
);
return $mech;
}
=head2 setup_instance($instance, $c, $model)
=cut
sub setup_instance {
my ($self, $instance, $c, $model) = @_;
$model->create_instance($c, {id => $instance, title => 'test instance'});
return;
}
=head2 setup_test_environment(%params)
%params may contain mechanize => 1 for optionally initializing $mech
=cut
sub setup_test_environment {
my ($self, %params) = @_;
my $instance = 'test' . int(10 + rand() * 99989) . '.example';
my $mech;
$mech = $self->init_mechanize if $params{mechanize};
my $c = CiderCMS->new;
my $model = $c->model('DB');
$self->setup_instance($instance, $c, $model);
return ($instance, $c, $model, $mech);
}
=head2 populate_types(%types)
=cut
sub populate_types {
my ($self, $types) = @_;
while (my ($type, $data) = each %$types) {
$model->create_type(
$c,
{
id => $type,
name => $data->{name} // $type,
page_element => $data->{page_element} // 0,
}
);
my $i = 0;
foreach my $attr (@{ $data->{attributes} }) {
$model->create_attribute($c, {
type => $type,
id => $attr->{id},
name => $data->{name} // ucfirst($attr->{id}),
sort_id => $i++,
data_type => $attr->{data_type} // ucfirst($attr->{id}),
repetitive => $attr->{repetitive} // 0,
mandatory => $attr->{mandatory} // 0,
default_value => $attr->{default_value},
});
}
if ($data->{template}) {
copy
"$Bin/test.example/templates/types/$data->{template}",
"$Bin/../root/instances/$instance/templates/types/$type.zpt"
or die "could not copy template $data->{template}";
}
}
}
+sub write_template {
+ my ($self, $file, $contents) = @_;
+
+ write_file("$Bin/../root/instances/$instance/templates/types/$file.zpt", $contents);
+}
+
=head2 END
On process exit, the test instance will be cleaned up again.
=cut
END {
if ($instance and $model) {
$model->dbh->do(q{set client_min_messages='warning'});
$model->dbh->do(qq{drop schema if exists "$instance" cascade});
$model->dbh->do(q{set client_min_messages='notice'});
remove_tree("$Bin/../root/instances/$instance");
}
}
1;
diff --git a/root/templates/login.zpt b/root/templates/login.zpt
index 629666f..6194ea7 100644
--- a/root/templates/login.zpt
+++ b/root/templates/login.zpt
@@ -1,40 +1,43 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
xml:lang="en"
lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
xmlns:i18n="http://xml.zope.org/namespaces/i18n"
i18n:domain="CiderCMS">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title tal:content="context/property --title 'CiderCMS Login'">CiderCMS Login</title>
<link rel="stylesheet" tal:attributes="href string:${uri_sys_static}/css/management.css" />
</head>
<body>
<h1>CiderCMS Login</h1>
<form action="" method="post">
<input type="hidden" name="referer" tal:attributes="value referer"/>
<input type="hidden" name="parent" value="2"/>
<input type="hidden" name="parent_attr" value="children"/>
<p tal:condition="true: message" tal:content="message"/>
<label>
<span>User name:</span>
<input type="text" name="username" tal:attributes="value username"/>
</label>
<label>
<span>Password:</span>
<input type="password" name="password"/>
</label>
<button type="submit">Login</button>
</form>
- <p tal:define="users context/object_by_id '2'" tal:condition="true: users/attribute --registration" class="registration">
- <a tal:define="registration users/attribute --registration" tal:attributes="href registration/data/0/uri_index">
+ <p
+ tal:define="users context/object_by_id '2'; registration users/property --registration undef"
+ tal:condition="true: registration"
+ class="registration">
+ <a tal:attributes="href registration/0/uri_index">
Neuen Benutzer registrieren
</a>
</p>
</body>
</html>
diff --git a/t/custom_registration.t b/t/custom_registration.t
index 927e614..31b513c 100644
--- a/t/custom_registration.t
+++ b/t/custom_registration.t
@@ -1,149 +1,213 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
-use File::Slurp qw(write_file);
use FindBin qw($Bin);
my ($root, $users, $restricted);
setup_test_instance();
test_registration_not_offered();
-setup_registration();
+setup_registration_objects();
test_registration();
done_testing;
sub setup_test_instance {
setup_types();
setup_objects();
}
sub setup_types {
setup_folder_type();
+ setup_textarea_type();
setup_userlist_type();
setup_user_type();
+ setup_registration_type();
}
sub setup_folder_type {
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
+ template => 'folder.zpt',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'restricted',
data_type => 'Boolean',
default_value => 0,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
+sub setup_textarea_type {
+ CiderCMS::Test->populate_types({
+ textarea => {
+ name => 'Textarea',
+ template => 'textarea.zpt',
+ page_element => 1,
+ attributes => [
+ {
+ id => 'text',
+ mandatory => 1,
+ },
+ ],
+ },
+ });
+}
+
sub setup_userlist_type {
CiderCMS::Test->populate_types({
userlist => {
name => 'User list',
attributes => [{
type => 'userlist',
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
},
],
},
});
}
sub setup_user_type {
CiderCMS::Test->populate_types({
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'email',
data_type => 'String',
mandatory => 1,
},
],
},
});
- write_file("$Bin/../root/instances/$instance/templates/types/user.zpt", q(<div
+ CiderCMS::Test->write_template('user', q(<div
xmlns:tal="http://purl.org/petal/1.0/"
tal:attributes="id string:object_${self/id}"
tal:content="self/property --username"
/>));
}
sub setup_objects {
$root = $model->get_object($c, 1);
$users = $root->create_child(
attribute => 'children',
type => 'userlist',
data => { title => 'Users' },
);
$restricted = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Restricted', restricted => 1 },
);
}
-sub setup_registration {
+sub setup_registration_type {
CiderCMS::Test->populate_types({
registration => {
- name => 'Registration',
+ name => 'Registration',
+ template => 'registration.zpt',
+ attributes => [
+ {
+ id => 'children',
+ data_type => 'Object',
+ },
+ {
+ id => 'success',
+ data_type => 'Object',
+ },
+ ],
},
});
+
$model->create_attribute($c, {
type => 'userlist',
id => 'registration',
name => 'Registration',
sort_id => 0,
data_type => 'Object',
repetitive => 0,
mandatory => 0,
default_value => '',
});
+}
- $users->create_child(
+sub setup_registration_objects {
+ my $registration = $users->create_child(
attribute => 'registration',
type => 'registration',
data => {},
);
+ $registration->create_child(
+ attribute => 'children',
+ type => 'textarea',
+ data => { text => 'Test' },
+ );
+ my $success = $registration->create_child(
+ attribute => 'success',
+ type => 'folder',
+ data => { title => 'Success' },
+ );
+ $success->create_child(
+ attribute => 'children',
+ type => 'textarea',
+ data => { text => 'Success! Please check your email.' },
+ );
}
-# Try accessing restricted content
sub test_registration_not_offered {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_lacks('Neuen Benutzer registrieren');
}
sub test_registration {
$mech->get_ok("http://localhost/$instance/restricted/index.html");
$mech->content_contains('Login');
$mech->content_contains('Neuen Benutzer registrieren');
+ $mech->follow_link_ok({text => 'Neuen Benutzer registrieren'});
+ $mech->submit_form_ok({
+ with_fields => {
+ username => 'testname',
+ password => 'testpass',
+ email => 'test@localhost',
+ },
+ });
+ $mech->content_contains('Success! Please check your email.');
+
+ $mech->get_ok("http://localhost/$instance/restricted/index.html");
+ $mech->content_contains('Login');
+ $mech->submit_form_ok({
+ with_fields => {
+ username => 'testname',
+ password => 'testpass',
+ },
+ });
}
diff --git a/t/test.example/templates/types/registration.zpt b/t/test.example/templates/types/registration.zpt
new file mode 100644
index 0000000..dd23d41
--- /dev/null
+++ b/t/test.example/templates/types/registration.zpt
@@ -0,0 +1,24 @@
+<form
+ xmlns:tal="http://purl.org/petal/1.0/"
+ xmlns:i18n="http://xml.zope.org/namespaces/i18n"
+ i18n:domain="CiderCMS"
+ tal:attributes="id string:object_${self/id}; action string:${context/uri}/register"
+ method="post"
+>
+ <div tal:condition="true: c/req/params/username">
+ <span tal:replace=""/>
+ </div>
+ <label>
+ <span>Benutzername:</span>
+ <input type="text" name="username" tal:attributes="value username"/>
+ </label>
+ <label>
+ <span>Passwort:</span>
+ <input type="password" name="password"/>
+ </label>
+ <label>
+ <span>Email:</span>
+ <input type="text" name="email" tal:attributes="value email"/>
+ </label>
+ <button type="submit">Registrieren</button>
+</form>
|
niner/CiderCMS
|
01432ebf83c75a0f1d24c45bf8648c15b1d69d3e
|
Catch creating child with invalid attribute names
|
diff --git a/lib/CiderCMS/Object.pm b/lib/CiderCMS/Object.pm
index 7d33d54..6cc3d26 100644
--- a/lib/CiderCMS/Object.pm
+++ b/lib/CiderCMS/Object.pm
@@ -1,566 +1,570 @@
package CiderCMS::Object;
use strict;
use warnings;
use Scalar::Util qw(weaken);
use List::MoreUtils qw(any);
use File::Path qw(mkpath);
use File::Copy qw(move);
+use Carp qw(croak);
use CiderCMS::Attribute;
=head1 NAME
CiderCMS::Object - Content objects
=head1 SYNOPSIS
See L<CiderCMS>
=head1 DESCRIPTION
This class is the base for all content objects and provides the public API that can be used in templates.
=head1 METHODS
=head2 new({c => $c, id => 2, type => 'type1', parent => 1, parent_attr => 'children', sort_id => 0, data => {}})
=cut
sub new {
my ($class, $params) = @_;
$class = ref $class if ref $class;
my $c = $params->{c};
my $stash = $c->stash;
my $type = $params->{type};
my $data = $params->{data};
my $self = bless {
c => $params->{c},
id => $params->{id},
parent => $params->{parent},
parent_attr => $params->{parent_attr},
level => $params->{level},
type => $type,
sort_id => $params->{sort_id} || 0,
dcid => $params->{dcid},
attr => $stash->{types}{$type}{attr},
attributes => $stash->{types}{$type}{attributes},
}, $class;
weaken($self->{c});
foreach my $attr (@{ $self->{attributes} }) {
my $id = $attr->{id};
$self->{data}{$id} = $attr->{class}->new({c => $c, object => $self, data => $data->{$id}, %$attr});
}
return $self;
}
=head2 object_by_id($id)
Returns an object for the given ID
=cut
sub object_by_id {
my ($self, $id) = @_;
return $self->{c}->model('DB')->get_object($self->{c}, $id);
}
=head2 type
Returns the type info for this object.
For example:
{
id => 'type1',
name => 'Type 1',
page_element => 0,
attributes => [
# same as {attrs}{attr1}
],
attr => {
attr1 => {
type => 'type1',
class => 'CiderCMS::Attribute::String',
id => 'attr1',
name => 'Attribute 1',
sort_id => 0,
data_type => 'String',
repetitive => 0,
mandatory => 1,
default_value => '',
},
},
},
=cut
sub type {
my ($self) = @_;
return $self->{c}->stash->{types}{$self->{type}};
}
=head2 property($property)
Returns the data of the named attribute
=cut
sub property {
my ($self, $property, $default) = @_;
unless (exists $self->{data}{$property}) {
return $default if @_ == 3;
die "unknown property $property";
}
return $self->{data}{$property}->data;
}
=head2 set_property($property, $data)
Sets the named attribute to the given value
=cut
sub set_property {
my ($self, $property, $data) = @_;
return $self->{data}{$property}->set_data($data);
}
=head2 attribute($attribute)
Returns the CiderCMS::Attribute object for the named attribute
=cut
sub attribute {
my ($self, $attribute) = @_;
return unless exists $self->{data}{$attribute};
return $self->{data}{$attribute};
}
=head2 update_data($data)
Updates this object's data from a hashref.
=cut
sub update_data {
my ($self, $data) = @_;
foreach (values %{ $self->{data} }) {
$_->set_data_from_form($data);
}
return;
}
=head2 init_defaults()
Initialize this object's data to the attributes' default values.
=cut
sub init_defaults {
my ($self) = @_;
$_->init_default foreach values %{ $self->{data} };
return;
}
=head2 parent
Returns the parent of this object, if any.
=cut
sub parent {
my ($self) = @_;
return unless $self->{parent};
return $self->{c}->model('DB')->get_object($self->{c}, $self->{parent}, $self->{level} - 1);
}
=head2 parent_by_level($level)
Returns the parent at a certain level.
The site object is at level 0.
=cut
sub parent_by_level {
my ($self, $level) = @_;
return if $self->{level} < $level; # already on a lower level
my $parent = $self;
while ($parent) {
return $parent if $parent->{level} == $level;
$parent = $parent->parent;
}
return;
}
=head2 children()
Returns the children of this object regardless to which attribute they belong.
Usually one should use $object->property('my_attribute') to only get the children of a certain attribute.
Returns a list in list context and an array ref in scalar context.
=cut
sub children {
my ($self) = @_;
return $self->{c}->model('DB')->object_children($self->{c}, $self);
}
=head2 uri()
Returns an URI without a file name for this object
=cut
sub uri {
my ($self) = @_;
my $parent = $self->parent;
my $dcid = ($self->{dcid} // $self->{id});
return ( ($parent ? $parent->uri : $self->{c}->uri_for_instance()) . ($dcid ? "/$dcid" : '') );
}
=head2 uri_index()
Returns an URI to the first object in this subtree that contains page elements.
If none does, return the URI to the first child.
=cut
sub uri_index {
my ($self) = @_;
my @children = $self->children;
if (not @children or any { $_->type->{page_element} } @children) { # we contain no children at all or page elements
return $self->uri . '/index.html';
}
else {
return $children[0]->uri_index;
}
}
=head2 uri_management()
Returns an URI to the management interface for this object
=cut
sub uri_management {
my ($self) = @_;
return $self->uri . '/manage';
}
=head2 uri_static()
Returns an URI for static file for this object
=cut
sub uri_static {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->uri_static : $self->{c}->uri_static_for_instance()) . "/$self->{id}" );
}
=head2 fs_path()
Returns the file system path to this node
=cut
sub fs_path {
my ($self) = @_;
my $parent = $self->parent;
return ( ($parent ? $parent->fs_path : $self->{c}->fs_path_for_instance()) . "/$self->{id}" );
}
=head2 edit_form($errors)
Renders the form for editing this object.
The optional $errors may be a hash reference with error messages for attributes.
=cut
sub edit_form {
my ($self, $errors) = @_;
$errors //= {};
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => 'edit.zpt',
self => $self,
attributes => [
map {
$self->{data}{$_->{id}}->input_field($errors->{$_->{id}})
} @{ $self->{attributes} },
],
});
}
=head2 render()
Returns an HTML representation of this object.
=cut
sub render {
my ($self) = @_;
my $c = $self->{c};
return $c->view()->render_template($c, {
%{ $c->stash },
template => "types/$self->{type}.zpt",
self => $self,
});
}
=head2 validate($data)
Validate the given data.
Returns a hash containing messages for violated constraints:
{
attr1 => ['missing'],
attr2 => ['invalid', 'wrong'],
}
=cut
sub validate {
my ($self, $data) = @_;
my %results;
foreach (values %{ $self->{data} }) {
my @result = $_->validate($data);
$results{ $_->{id} } = \@result if @result;
}
return \%results if keys %results;
return;
}
=head2 prepare_attributes()
Prepares attributes for insert and update operations.
=cut
sub prepare_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->prepare_update();
}
return;
}
=head2 update_attributes()
Runs update operation on attributes after inserts and updates.
=cut
sub update_attributes {
my ($self) = @_;
foreach (values %{ $self->{data} }) {
$_->post_update();
}
return;
}
=head2 insert({after => $after})
Inserts the object into the database.
=cut
sub insert {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data(delete $params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->insert_object($self->{c}, $self, $params);
$self->update_attributes;
return $result;
}
=head2 update()
Updates the object in the database.
=cut
sub update {
my ($self, $params) = @_;
if ($params->{data}) {
$self->update_data($params->{data});
}
$self->prepare_attributes;
my $result = $self->{c}->model('DB')->update_object($self->{c}, $self);
$self->update_attributes;
return $result;
}
=head2 delete_from_db()
Deletes the object and it's children.
=cut
sub delete_from_db {
my ($self) = @_;
foreach ($self->children) {
$_->delete_from_db;
}
return $self->{c}->model('DB')->delete_object($self->{c}, $self);
}
=head2 get_dirty_columns()
Returns two array refs with column names and corresponding values.
=cut
sub get_dirty_columns {
my ($self) = @_;
my (@columns, @values);
foreach (@{ $self->{attributes} }) {
my $id = $_->{id};
my $attr = $self->{data}{$id};
if ($attr->db_type) {
push @columns, $id;
push @values, $attr->{data}; #TODO introduce an $attr->raw_data
}
}
return \@columns, \@values;
}
=head2 move_to(parent => $parent, after => $after)
Moves this object (and it's subtree) to a new parent and or sort position
=cut
sub move_to {
my ($self, %params) = @_;
my $old_fs_path = $self->fs_path;
my $result = $self->{c}->model('DB')->move_object($self->{c}, $self, \%params);
if (-e $old_fs_path) {
my $new_fs_path = $self->fs_path;
mkpath $self->parent->fs_path if $self->{parent};
move $old_fs_path, $new_fs_path;
}
return $result;
}
=head2 new_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in memory for the given attribute.
=cut
sub new_child {
my ($self, %params) = @_;
$params{c} = $self->{c};
$params{parent} = $self->{id};
$params{level} = $self->{level};
$params{parent_attr} = delete $params{attribute};
+ croak "Invalid attribute: $params{parent_attr}"
+ unless exists $self->{data}{ $params{parent_attr} };
+
return CiderCMS::Object->new(\%params);
}
=head2 create_child(attribute => $attribute, type => $type, data => $data)
Creates a child object in the database for the given attribute.
=cut
sub create_child {
my ($self, %params) = @_;
# Don't give data to new_child. Instead give it to insert so it gets treated like
# data subitted through the management UI.
my $data = delete $params{data};
my $child = $self->new_child(%params);
$child->insert({data => $data});
return $child;
}
=head2 user_has_access
Returns whether the currently logged in user has access to this folder and all
parent folders.
=cut
sub user_has_access {
my ($self) = @_;
return (not $self->property('restricted', 0) or $self->{c}->user);
}
=head1 AUTHOR
Stefan Seifert
=head1 LICENSE
This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
|
niner/CiderCMS
|
aa3e17937bb1793a380bec14663bf38648a6fd75
|
Offer a link to user registration on login screen
|
diff --git a/root/templates/login.zpt b/root/templates/login.zpt
index cb48a57..629666f 100644
--- a/root/templates/login.zpt
+++ b/root/templates/login.zpt
@@ -1,35 +1,40 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
xml:lang="en"
lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
xmlns:i18n="http://xml.zope.org/namespaces/i18n"
i18n:domain="CiderCMS">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title tal:content="context/property --title 'CiderCMS Login'">CiderCMS Login</title>
<link rel="stylesheet" tal:attributes="href string:${uri_sys_static}/css/management.css" />
</head>
<body>
<h1>CiderCMS Login</h1>
<form action="" method="post">
<input type="hidden" name="referer" tal:attributes="value referer"/>
<input type="hidden" name="parent" value="2"/>
<input type="hidden" name="parent_attr" value="children"/>
<p tal:condition="true: message" tal:content="message"/>
<label>
<span>User name:</span>
<input type="text" name="username" tal:attributes="value username"/>
</label>
<label>
<span>Password:</span>
<input type="password" name="password"/>
</label>
<button type="submit">Login</button>
</form>
+ <p tal:define="users context/object_by_id '2'" tal:condition="true: users/attribute --registration" class="registration">
+ <a tal:define="registration users/attribute --registration" tal:attributes="href registration/data/0/uri_index">
+ Neuen Benutzer registrieren
+ </a>
+ </p>
</body>
</html>
diff --git a/t/custom_registration.t b/t/custom_registration.t
new file mode 100644
index 0000000..927e614
--- /dev/null
+++ b/t/custom_registration.t
@@ -0,0 +1,149 @@
+use strict;
+use warnings;
+use utf8;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+use File::Slurp qw(write_file);
+use FindBin qw($Bin);
+
+my ($root, $users, $restricted);
+setup_test_instance();
+test_registration_not_offered();
+setup_registration();
+test_registration();
+
+done_testing;
+
+sub setup_test_instance {
+ setup_types();
+ setup_objects();
+}
+
+sub setup_types {
+ setup_folder_type();
+ setup_userlist_type();
+ setup_user_type();
+}
+
+sub setup_folder_type {
+ CiderCMS::Test->populate_types({
+ folder => {
+ name => 'Folder',
+ attributes => [
+ {
+ id => 'title',
+ mandatory => 1,
+ },
+ {
+ id => 'restricted',
+ data_type => 'Boolean',
+ default_value => 0,
+ },
+ {
+ id => 'children',
+ data_type => 'Object',
+ },
+ ],
+ },
+ });
+}
+
+sub setup_userlist_type {
+ CiderCMS::Test->populate_types({
+ userlist => {
+ name => 'User list',
+ attributes => [{
+ type => 'userlist',
+ id => 'title',
+ mandatory => 1,
+ },
+ {
+ id => 'children',
+ data_type => 'Object',
+ },
+ ],
+ },
+ });
+}
+
+sub setup_user_type {
+ CiderCMS::Test->populate_types({
+ user => {
+ name => 'User',
+ page_element => 1,
+ attributes => [
+ {
+ id => 'username',
+ data_type => 'String',
+ mandatory => 1,
+ },
+ {
+ id => 'password',
+ mandatory => 1,
+ },
+ {
+ id => 'email',
+ data_type => 'String',
+ mandatory => 1,
+ },
+ ],
+ },
+ });
+ write_file("$Bin/../root/instances/$instance/templates/types/user.zpt", q(<div
+ xmlns:tal="http://purl.org/petal/1.0/"
+ tal:attributes="id string:object_${self/id}"
+ tal:content="self/property --username"
+ />));
+}
+
+sub setup_objects {
+ $root = $model->get_object($c, 1);
+ $users = $root->create_child(
+ attribute => 'children',
+ type => 'userlist',
+ data => { title => 'Users' },
+ );
+ $restricted = $root->create_child(
+ attribute => 'children',
+ type => 'folder',
+ data => { title => 'Restricted', restricted => 1 },
+ );
+}
+
+sub setup_registration {
+ CiderCMS::Test->populate_types({
+ registration => {
+ name => 'Registration',
+ },
+ });
+ $model->create_attribute($c, {
+ type => 'userlist',
+ id => 'registration',
+ name => 'Registration',
+ sort_id => 0,
+ data_type => 'Object',
+ repetitive => 0,
+ mandatory => 0,
+ default_value => '',
+ });
+
+ $users->create_child(
+ attribute => 'registration',
+ type => 'registration',
+ data => {},
+ );
+}
+
+# Try accessing restricted content
+sub test_registration_not_offered {
+ $mech->get_ok("http://localhost/$instance/restricted/index.html");
+ $mech->content_contains('Login');
+ $mech->content_lacks('Neuen Benutzer registrieren');
+}
+
+sub test_registration {
+ $mech->get_ok("http://localhost/$instance/restricted/index.html");
+ $mech->content_contains('Login');
+ $mech->content_contains('Neuen Benutzer registrieren');
+}
|
niner/CiderCMS
|
ab609f038c9437d4c62cbab8d66e29d5effa70b7
|
Fix tests failing after 4fccfee3
|
diff --git a/root/templates/custom/reservation/reservations.zpt b/root/templates/custom/reservation/reservations.zpt
index 08961fa..629d715 100644
--- a/root/templates/custom/reservation/reservations.zpt
+++ b/root/templates/custom/reservation/reservations.zpt
@@ -1,48 +1,48 @@
<div
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
metal:define-macro="list"
tal:define="
reservations_attr context/attribute --reservations;
reservations_search reservations_attr/search --cancelled_by undef --start 'future';
reservations_sorted reservations_search/sort --start --end;
reservations reservations_sorted/list;
active_reservation_search reservations_attr/search --cancelled_by undef --start 'past' --start 'today' --end 'future';
active_reservation active_reservation_search/list
">
<p tal:condition="false: active_reservation" class="no_active_reservation">Frei</p>
<p tal:condition="false: reservations" class="no_reservations" id="reservations">
Keine Reservierungen eingetragen.
</p>
<table tal:condition="true: reservations" class="reservations" id="reservations">
<thead>
<tr>
<th>Datum</th>
<th>Von</th>
<th>Bis</th>
<th>Pilot</th>
</tr>
</thead>
<tbody tal:repeat="reservation reservations">
<tr tal:define="start reservation/attribute --start">
<td class="start_date" tal:attributes="data-date start/ymd">
<span tal:condition="false: start/is_today" tal:content="start/ymd"/>
- <span tal:condition="true: start/is_today">Heute</td>
+ <span tal:condition="true: start/is_today">Heute</span>
</td>
<td class="start_time" tal:content="start/format '%H:%M'"/>
<td class="end_time" tal:define="end reservation/attribute --end" tal:content="end/format '%H:%M'"/>
<td class="user" tal:content="reservation/property --user"/>
<td>
<a class="cancel" tal:attributes="href string:${context/uri}/cancel/${reservation/id}">stornieren</a>
</td>
</tr>
<tr tal:condition="true: reservation/property --info">
<td class="info" colspan="5" tal:content="reservation/property --info"/>
</tr>
</tbody>
</table>
<a tal:condition="false:reservation" tal:attributes="href string:${self/uri}/reserve">Neue Reservierung</a>
</div>
diff --git a/t/17_custom_reservation.t b/t/17_custom_reservation.t
index 3bfd3b3..caff3c4 100644
--- a/t/17_custom_reservation.t
+++ b/t/17_custom_reservation.t
@@ -1,264 +1,264 @@
use strict;
use warnings;
use utf8;
use CiderCMS::Test (test_instance => 1, mechanize => 1);
use Test::More;
use File::Slurp;
CiderCMS::Test->populate_types({
folder => {
name => 'Folder',
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'children',
data_type => 'Object',
repetitive => 1,
},
],
},
user => {
name => 'User',
page_element => 1,
attributes => [
{
id => 'username',
data_type => 'String',
mandatory => 1,
},
{
id => 'password',
mandatory => 1,
},
{
id => 'name',
data_type => 'String',
},
],
},
reservation => {
name => 'Reservation',
page_element => 1,
attributes => [
{
id => 'start',
data_type => 'DateTime',
mandatory => 1,
},
{
id => 'end',
data_type => 'Time',
mandatory => 1,
},
{
id => 'user',
data_type => 'String',
},
{
id => 'info',
data_type => 'String',
},
{
id => 'cancelled_by',
data_type => 'String',
},
],
},
airplane => {
name => 'Airplane',
page_element => 1,
attributes => [
{
id => 'title',
mandatory => 1,
},
{
id => 'reservations',
data_type => 'Object',
repetitive => 1,
},
{
id => 'reservation_time_limit',
data_type => 'Integer',
},
],
template => 'airplane.zpt'
},
});
my $root = $model->get_object($c, 1);
my $users = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Users' },
);
$users->create_child(
attribute => 'children',
type => 'user',
data => {
username => 'test',
name => 'test',
password => 'test',
},
);
my $airplanes = $root->create_child(
attribute => 'children',
type => 'folder',
data => { title => 'Airplanes' },
);
my $dimona = $airplanes->create_child(
attribute => 'children',
type => 'airplane',
data => {
title => 'Dimona',
},
);
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
$mech->content_contains('Keine Reservierungen eingetragen.');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
username => 'test',
password => 'test',
},
});
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
$mech->content_lacks('Keine Reservierungen eingetragen.');
- ok($mech->find_xpath(qq{//td[text()="Heute"]}), "Today's reservation listed");
+ ok($mech->find_xpath(qq{//td[span="Heute"]}), "Today's reservation listed");
ok($mech->find_xpath(qq{//td[text()="test"]}), 'reserving user listed');
ok($mech->find_xpath(qq{//td[text()="Testflug"]}), 'Info listed');
$date->add(days => 1);
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 1)->hour . ':00',
end => $date->clone->add(hours => 2)->hour . ':30',
info => 'Testflug',
},
button => 'save',
});
- ok($mech->find_xpath(q{//td[text()="Heute"]}), "Today's reservation still listed");
- ok($mech->find_xpath(q{//td[text()="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
+ ok($mech->find_xpath(q{//td[span="Heute"]}), "Today's reservation still listed");
+ ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation listed");
$mech->get_ok(
$mech->find_xpath(q{//tr[td="Heute"]/td/a[@class="cancel"]/@href}),
'cancel reservation'
);
is('' . $mech->find_xpath(q{//td[text()="Heute"]}), '', "Today's reservation gone");
- ok($mech->find_xpath(q{//td[text()="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
+ ok($mech->find_xpath(q{//td[span="} . $date->ymd . q{"]}), "Tomorrow's reservation still listed");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/6/manage");
is($mech->value('cancelled_by'), 'test');
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->add(hours => 2)->hour . ':00',
end => $date->clone->add(hours => 3)->hour . ':30',
info => 'Testflug2',
},
button => 'save',
});
ok(
$mech->find_xpath('//span[text() = "conflicting existent reservation"]'),
'error message for conflict with existent reservation found'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
# test error handling
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
$mech->submit_form_ok({
with_fields => {
start_date => 'invalid',
start_time => 'nonsense',
end => 'forget',
info => '',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "invalid"]'), 'error message for invalid date found');
$model->dbh->rollback;
});
$model->txn_do(sub {
# Update to test advance time limit
$dimona->set_property(reservation_time_limit => 24);
$dimona->update;
my $now = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->clone->add(hours => 1)->hms,
end => $now->clone->add(hours => 2)->hms,
info => 'too close',
},
button => 'save',
});
ok($mech->find_xpath('//span[text() = "too close"]'), 'error message for too close date found');
$now = DateTime->now->add(days => 2)->add(hours => 4);
$mech->submit_form_ok({
with_fields => {
start_date => $now->ymd,
start_time => $now->hms,
end => $now->clone->add(hours => 1)->hms,
info => 'too close',
},
button => 'save',
});
is(
'' . $mech->find_xpath('//span[text() = "too close"]'),
'',
'error message for too close date gone'
);
$model->dbh->rollback;
});
$model->txn_do(sub {
$mech->get_ok("http://localhost/$instance/airplanes/dimona/index.html");
ok($mech->find_xpath(qq{//p[text()="Frei"]}), "No reservation active for now");
$mech->get_ok("http://localhost/$instance/airplanes/dimona/reserve");
my $date = DateTime->now;
$mech->submit_form_ok({
with_fields => {
start_date => $date->ymd,
start_time => $date->clone->subtract(hours => 1)->hms(':'),
end => $date->clone->add(hours => 2)->hour . ':00',
info => 'Testflug',
},
button => 'save',
});
is('' . $mech->find_xpath(qq{//p[text()="Frei"]}), '', "Reservation active for now");
$model->dbh->rollback;
});
done_testing;
|
niner/CiderCMS
|
92ecf16ef60d52a0508f42a84929f0032582ed22
|
Plain text attributes
|
diff --git a/lib/CiderCMS/Attribute/Plaintext.pm b/lib/CiderCMS/Attribute/Plaintext.pm
new file mode 100644
index 0000000..168de76
--- /dev/null
+++ b/lib/CiderCMS/Attribute/Plaintext.pm
@@ -0,0 +1,33 @@
+package CiderCMS::Attribute::Plaintext;
+
+use strict;
+use warnings;
+
+use base qw(CiderCMS::Attribute::String);
+
+=head1 NAME
+
+CiderCMS::Attribute::Plaintext - Plain text attribute
+
+=head1 SYNOPSIS
+
+See L<CiderCMS::Attribute>
+
+=head1 DESCRIPTION
+
+HTML code attribute.
+
+=head1 METHODs
+
+=head1 AUTHOR
+
+Stefan Seifert
+
+=head1 LICENSE
+
+This library is free software, you can redistribute it and/or modify
+it under the same terms as Perl itself.
+
+=cut
+
+1;
diff --git a/root/templates/attributes/plaintext.zpt b/root/templates/attributes/plaintext.zpt
new file mode 100644
index 0000000..452d334
--- /dev/null
+++ b/root/templates/attributes/plaintext.zpt
@@ -0,0 +1,5 @@
+<label xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS">
+ <span tal:content="self/name"/>
+
+ <textarea tal:attributes="name self/id" cols="50" rows="10" tal:content="self/data"/>
+</label>
diff --git a/t/Attribute-Plaintext.t b/t/Attribute-Plaintext.t
new file mode 100644
index 0000000..35fefa8
--- /dev/null
+++ b/t/Attribute-Plaintext.t
@@ -0,0 +1,36 @@
+use strict;
+use warnings;
+use utf8;
+
+use CiderCMS::Test (test_instance => 1, mechanize => 1);
+use Test::More;
+
+CiderCMS::Test->populate_types({
+ tester => {
+ name => 'Tester',
+ attributes => [
+ {
+ id => 'code',
+ data_type => 'Plaintext',
+ mandatory => 0,
+ },
+ ],
+ page_element => 1,
+ template => 'plaintext_test.zpt',
+ },
+});
+
+$mech->get_ok("http://localhost/$instance/manage");
+$mech->follow_link_ok({ url_regex => qr{manage_add\b.*\btype=tester} }, 'Add a tester');
+
+$mech->submit_form_ok({
+ with_fields => {
+ code => "Foo\n Bar",
+ },
+ button => 'save',
+});
+
+$mech->get_ok("http://localhost/$instance/index.html");
+is('' . $mech->find_xpath('//code'), "Foo Bar", 'code displayed with white space');
+
+done_testing;
diff --git a/t/test.example/templates/types/plaintext_test.zpt b/t/test.example/templates/types/plaintext_test.zpt
new file mode 100644
index 0000000..fa70783
--- /dev/null
+++ b/t/test.example/templates/types/plaintext_test.zpt
@@ -0,0 +1 @@
+<code xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS" tal:attributes="id string:object_${self/id}" tal:content="self/property --code"/>
|
niner/CiderCMS
|
080bd4ff9b4c07cc8abdf3bad0ca9731b9b85be3
|
Fix date picker in reservation system
|
diff --git a/root/templates/custom/reservation/reserve.zpt b/root/templates/custom/reservation/reserve.zpt
index 6c511b9..0a41700 100644
--- a/root/templates/custom/reservation/reserve.zpt
+++ b/root/templates/custom/reservation/reserve.zpt
@@ -1,40 +1,40 @@
<div
xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
>
<div tal:replace="structure context/render"/>
<form action="#reservations" name="new_reservation" class="new_reservation" method="post">
<fieldset>
<legend>Neue Reservierung eintragen</legend>
<label class="required date">
<span>Datum <span class="errors" tal:condition="true: errors/start" tal:content="errors/start"/></span>
<input type="date" name="start_date" tal:attributes="value start_date"/>
<script type="text/javascript" tal:attributes="src string:${uri_sys_static}/js/calendar.js" />
<script type="text/javascript" tal:content="string:A_TCALDEF['imgpath'] = '${uri_sys_static}/images/calendar/'" />
<script type="text/javascript">
- new tcal ({'formname': 'new_reservation', 'controlname': 'date'});
+ new tcal ({'formname': 'new_reservation', 'controlname': 'start_date'});
</script>
</label>
<label class="start">
<span>Von </span>
<input type="time" name="start_time" tal:attributes="value start_time"/>
</label>
<label class="end">
<span>Bis <span class="errors" tal:condition="true: errors/end" tal:content="errors/end"/></span>
<input type="time" name="end" tal:attributes="value end"/>
</label>
<label class="user">
<span>Pilot <span class="errors" tal:condition="true: errors/user" tal:content="errors/user"/></span>
<input type="text" name="user" tal:attributes="value user"/>
</label>
<label class="info">
<span>Info <span class="errors" tal:condition="true: errors/info" tal:content="errors/info"/></span>
<textarea name="info" tal:content="info"/>
</label>
<button type="submit" name="save" value="1">Reservieren</button>
</fieldset>
</form>
</div>
|
niner/CiderCMS
|
4fccfee34efd1a59b122ef318be50f221df7a98a
|
Remove invalid nesting of tbody in reservations list
|
diff --git a/root/templates/custom/reservation/reservations.zpt b/root/templates/custom/reservation/reservations.zpt
index cee82a1..08961fa 100644
--- a/root/templates/custom/reservation/reservations.zpt
+++ b/root/templates/custom/reservation/reservations.zpt
@@ -1,48 +1,48 @@
<div
xmlns:tal="http://purl.org/petal/1.0/"
xmlns:metal="http://xml.zope.org/namespaces/metal"
metal:define-macro="list"
tal:define="
reservations_attr context/attribute --reservations;
reservations_search reservations_attr/search --cancelled_by undef --start 'future';
reservations_sorted reservations_search/sort --start --end;
reservations reservations_sorted/list;
active_reservation_search reservations_attr/search --cancelled_by undef --start 'past' --start 'today' --end 'future';
active_reservation active_reservation_search/list
">
<p tal:condition="false: active_reservation" class="no_active_reservation">Frei</p>
<p tal:condition="false: reservations" class="no_reservations" id="reservations">
Keine Reservierungen eingetragen.
</p>
<table tal:condition="true: reservations" class="reservations" id="reservations">
<thead>
<tr>
<th>Datum</th>
<th>Von</th>
<th>Bis</th>
<th>Pilot</th>
</tr>
</thead>
- <tbody>
- <tbody tal:repeat="reservation reservations">
- <tr tal:define="start reservation/attribute --start">
- <td tal:condition="false: start/is_today" tal:content="start/ymd"/>
- <td tal:condition="true: start/is_today">Heute</td>
- <td tal:content="start/format '%H:%M'"/>
- <td tal:define="end reservation/attribute --end" tal:content="end/format '%H:%M'"/>
- <td tal:content="reservation/property --user"/>
- <td>
- <a class="cancel" tal:attributes="href string:${context/uri}/cancel/${reservation/id}">stornieren</a>
- </td>
- </tr>
- <tr tal:condition="true: reservation/property --info">
- <td class="info" colspan="5" tal:content="reservation/property --info"/>
- </tr>
- </tbody>
+ <tbody tal:repeat="reservation reservations">
+ <tr tal:define="start reservation/attribute --start">
+ <td class="start_date" tal:attributes="data-date start/ymd">
+ <span tal:condition="false: start/is_today" tal:content="start/ymd"/>
+ <span tal:condition="true: start/is_today">Heute</td>
+ </td>
+ <td class="start_time" tal:content="start/format '%H:%M'"/>
+ <td class="end_time" tal:define="end reservation/attribute --end" tal:content="end/format '%H:%M'"/>
+ <td class="user" tal:content="reservation/property --user"/>
+ <td>
+ <a class="cancel" tal:attributes="href string:${context/uri}/cancel/${reservation/id}">stornieren</a>
+ </td>
+ </tr>
+ <tr tal:condition="true: reservation/property --info">
+ <td class="info" colspan="5" tal:content="reservation/property --info"/>
+ </tr>
</tbody>
</table>
<a tal:condition="false:reservation" tal:attributes="href string:${self/uri}/reserve">Neue Reservierung</a>
</div>
|
niner/CiderCMS
|
a55bcb8bc58decb120e713ca74052d4a0cfc5a7c
|
Fix date picker for DateTime attributes
|
diff --git a/root/templates/attributes/datetime.zpt b/root/templates/attributes/datetime.zpt
index 66377fa..0625d4e 100644
--- a/root/templates/attributes/datetime.zpt
+++ b/root/templates/attributes/datetime.zpt
@@ -1,7 +1,7 @@
<label xmlns:tal="http://purl.org/petal/1.0/" xmlns:i18n="http://xml.zope.org/namespaces/i18n" i18n:domain="CiderCMS">
<span tal:content="self/name"/>
<span class="errors" tal:condition="true: errors" tal:content="errors"/>
<input type="text" size="10" tal:attributes="name string:${self/id}_date; value if: self/data then: self/ymd else: undef"/>
- <script type="text/javascript" tal:content="string:new tcal ({'formname': 'edit_object_form', 'controlname': '${self/id}'})"/>
+ <script type="text/javascript" tal:content="string:new tcal ({'formname': 'edit_object_form', 'controlname': '${self/id}_date'})"/>
<input type="time" size="5" tal:attributes="name string:${self/id}_time; value if: self/data then: self/time else: undef"/>
</label>
|
niner/CiderCMS
|
45bfb967fcbcbec907e649b455364fa6c426d521
|
Add vim swap files to .gitignore
|
diff --git a/.gitignore b/.gitignore
index a3fd0d9..0998a95 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,13 +1,14 @@
Makefile.old
META.yml
MYMETA.json
MYMETA.yml
Makefile
Makefile.old
blib/
cover_db/
inc/
pm_to_blib
root/instances/
import.sh
.prove
+.*.swp
|
webcracy/activity_streams-workshop
|
a8d9d1efa1385e7d5b6519796e112285d836c724
|
added verb to json output
|
diff --git a/app/models/activity.rb b/app/models/activity.rb
index 2dadeb4..f6a2cd0 100644
--- a/app/models/activity.rb
+++ b/app/models/activity.rb
@@ -1,132 +1,133 @@
class Activity < ActiveRecord::Base
include ActionView::Helpers
include ActionController::UrlWriter
default_url_options[:host] = APP_CONFIG[:domain]
attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang
attr_accessible :actor_attributes, :target_attributes, :object_attributes
has_many :activity_objects, :dependent => :destroy
has_one :actor
has_one :object, :class_name => 'Obj'
has_one :target
belongs_to :user
named_scope :reverse, :order => 'created_at DESC'
named_scope :are_public, :conditions => {:is_public => true}
validates_presence_of :actor
validates_presence_of :verb
validates_presence_of :object
validates_presence_of :published_at
validates_presence_of :public_name, :if => Proc.new { |a| a.is_public }
before_create :add_permalink
accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? }
def self.verbs_to_select
[
['POST', "http://activitystrea.ms/schema/1.0/post"],
['FAVORITE', "http://activitystrea.ms/schema/1.0/favorite"],
['FOLLOW', 'http://activitystrea.ms/schema/1.0/follow'],
['LIKE', 'http://activitystrea.ms/schema/1.0/like'],
['MAKE-FRIEND', 'http://activitystrea.ms/schema/1.0/make-friend'],
['JOIN', 'http://activitystrea.ms/schema/1.0/join'],
['PLAY', 'http://activitystrea.ms/schema/1.0/play'],
['SAVE', 'http://activitystrea.ms/schema/1.0/save'],
['SHARE', 'http://activitystrea.ms/schema/1.0/share'],
['TAG', 'http://activitystrea.ms/schema/1.0/tag'],
['UPDATE', 'http://activitystrea.ms/schema/1.0/update']
]
end
def verb_title
verb.split('/').last.upcase
end
def to_json
a = {
:id => activity_url(self),
:permalinkUrl => activity_url(self),
:title => self.title,
:summary => self.summary,
:postedTime => self.published_at.to_s(:w3cdtf),
:actor => {
:id => self.actor.url_id,
:title => self.actor.title,
},
:object => {
:id => self.object.url_id,
:title => self.object.title,
:objectType => self.object.object_type
- }
+ },
+ :verb => self.verb
}
if self.target.present?
a[:target] = {
:id => self.target.url_id,
:title => self.target.title,
:objectType => self.target.object_type
}
end
return JSON.pretty_generate({
:data => {
:lang => "en-US",
:id => self.id,
:items => [ a ]
}
}.stringify_keys)
end
def to_xml
builder = Builder::XmlMarkup.new(:indent => 2)
builder.entry do |b|
b.id activity_url(self)
b.permalink activity_url(self)
b.published self.published_at.to_s(:w3cdtf)
b.title self.title
b.summary self.summary
b.author do
b.id self.actor.url_id
b.title self.actor.title
end
b.activity :verb, self.verb
b.activity :actor do
b.id self.actor.url_id
b.title self.actor.title, :type => 'text'
end
b.activity :object do
b.id self.object.url_id
b.title self.object.title, :type => 'text'
b.activity :"object-type", self.object.object_type
end
if self.target.present?
b.activity :target do
b.id self.target.url_id
b.title self.target.title, :type => 'text'
b.activity :"object-type", self.target.object_type
end
end
end
end
def add_permalink
hash = hash_gen(self)
while Activity.find_by_permalink(hash)
self.add_permalink
end
self.permalink = hash
end
private
def hash_gen(activity)
return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s
end
end
|
webcracy/activity_streams-workshop
|
1f37156eff3032b06a2f4c91d61bef78119f4cf7
|
created privacy page. further integrated janrain engage
|
diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb
index bfccb48..64f52ea 100644
--- a/app/controllers/home_controller.rb
+++ b/app/controllers/home_controller.rb
@@ -1,6 +1,8 @@
class HomeController < ApplicationController
def index
end
def faq
end
+ def privacy
+ end
end
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index e2ad4eb..2181f03 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,52 +1,56 @@
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => [:rpx_token] # RPX does not pass Rails form tokens...
# render new.rhtml
def new
redirect_to oauth_consumers_path
end
def create
logout_keeping_session!
user = User.authenticate(params[:login], params[:password])
if user
# Protects against session fixation attacks, causes request forgery
# protection if user resubmits an earlier form using back
# button. Uncomment if you understand the tradeoffs.
# reset_session
self.current_user = user
new_cookie_flag = (params[:remember_me] == "1")
handle_remember_cookie! new_cookie_flag
redirect_back_or_default('/')
flash[:notice] = "Logged in successfully"
else
note_failed_signin
@login = params[:login]
@remember_me = params[:remember_me]
render :action => 'new'
end
end
def destroy
logout_killing_session!
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
# user_data
# found: {:name=>'John Doe', :username => 'john', :email=>'[email protected]', :identifier=>'blug.google.com/openid/dsdfsdfs3f3'}
# not found: nil (can happen with e.g. invalid tokens)
def rpx_token
raise "hackers?" unless data = RPXNow.user_data(params[:token])
- self.current_user = User.find_by_email(data[:email]) || User.create!(data)
+ unless data[:email].nil?
+ self.current_user = User.find_by_email(data[:email]) || User.create!(data)
+ else
+ self.current_user = User.find_by_login(data[:username]) || User.create!(data)
+ end
redirect_to '/'
end
protected
# Track failed login attempts
def note_failed_signin
flash[:error] = "Couldn't log you in as '#{params[:login]}'"
logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}"
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 57139d0..aef3f17 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,54 +1,52 @@
require 'digest/sha1'
class User < ActiveRecord::Base
include Authentication
#include Authentication::ByPassword
include Authentication::ByCookieToken
# validates_presence_of :login
# validates_length_of :login, :within => 3..40
# validates_uniqueness_of :login
# validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
- validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true
- validates_length_of :name, :maximum => 100
+ #validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true
+ #validates_length_of :name, :maximum => 100
- validates_presence_of :email
- validates_length_of :email, :within => 6..100 #[email protected]
- validates_uniqueness_of :email
- validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message
+ # validates_uniqueness_of :email
+ #validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message
has_many :activities, :dependent => :destroy
# HACK HACK HACK -- how to do attr_accessible from here?
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :name, :password, :password_confirmation
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
#
# uff. this is really an authorization, not authentication routine.
# We really need a Dispatch Chain here or something.
# This will also let us return a human error message.
#
def self.authenticate(login, password)
return nil if login.blank? || password.blank?
u = find_by_login(login.downcase) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
def login=(value)
write_attribute :login, (value ? value.downcase : nil)
end
def email=(value)
write_attribute :email, (value ? value.downcase : nil)
end
protected
end
diff --git a/app/views/home/privacy.html.haml b/app/views/home/privacy.html.haml
new file mode 100644
index 0000000..413f26a
--- /dev/null
+++ b/app/views/home/privacy.html.haml
@@ -0,0 +1,13 @@
+-title "Privacy Policy"
+
+%h3 Data we collect
+
+%p Depending on the Identity Provider you use to login, we store <strong>either</strong> your email, your name or your username, as provided by the service.
+
+%h3 What we do with it
+
+%p We don't sell it, we don't use it to contact you, we don't give it to third parties. We only use it for authentication purposes and it is stored safely in our database.
+
+%h3 Questions and concerns
+
+%p You can write an email to <em><code>alex_at_webcracy.org</code></em> with your questions or concerns.
\ No newline at end of file
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 5000199..36757c9 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,45 +1,45 @@
!!! Strict
%html{html_attrs}
%head
%title
= h(yield(:title).to_s + ' - Activity Streams Workshop')
%meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}
%meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
%meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
#page
#header
#top
%h1{:style => 'float: left;'} Activity Streams Workshop
#user_bar{:style => 'float: right; text-align: right; '}
= render :partial => 'users/user_bar'
.clear
#nav
%ul.nav
%li
%a{:href => '/'} Home
%li
%a{:href => '/activities/new'} New activity
%li
%a{:href => '/activities'} Browse Activities
%li
%a{:href => '/faq'} FAQ
.clear
#content
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
- if show_title?
%h2=h yield(:title)
= yield
#footer
%p
Check out the <a href="http://activitystrea.ms" title="Activity Streams Website">Activity Streams</a> website. Grab the app's <a href="http://github.com/webcracy/activity_streams-workshop" title="Activity Streams Workshop code on Github">code</a>.
Please report any <a href="http://github.com/webcracy/activity_streams-workshop/issues" title="Activity Streams Workshop issues on Github">issues</a>.
%br
- Created by <a href="http://0x82.com" title="Ruben Fonseca">Ruben Fonseca</a> and <a href="http://webcracy.org" title="Webcracy.org">Alex Solleiro</a> in 2010.
\ No newline at end of file
+ Created by <a href="http://0x82.com" title="Ruben Fonseca">Ruben Fonseca</a> and <a href="http://webcracy.org" title="Webcracy.org">Alex Solleiro</a> in 2010. <a href="/privacy" title="Privacy Policy">Privacy</a>.
\ No newline at end of file
diff --git a/app/views/users/_user_bar.html.erb b/app/views/users/_user_bar.html.erb
index e15c1a2..573f3d3 100644
--- a/app/views/users/_user_bar.html.erb
+++ b/app/views/users/_user_bar.html.erb
@@ -1,9 +1,9 @@
<% if logged_in? -%>
<div id="user-bar-greeting">
- Logged in as <%= current_user.email %>
+ Logged in as <%= current_user.email || current_user.name %>
<!-- <%= link_to_current_user :content_method => :login %> -->
</div>
<div id="user-bar-action" style="text-align: right;">
(<%= link_to "Log out", logout_path, { :title => "Log out" } %>)
</div>
<% end -%>
diff --git a/config/routes.rb b/config/routes.rb
index c373565..1e5c365 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,15 +1,16 @@
ActionController::Routing::Routes.draw do |map|
map.resources :activities, :member => { :publish => :post }
map.resources :oauth_consumers,:member=>{:callback=>:get}
map.resources :users
map.resource :session, :member=>{:rpx_token => [:get, :post]}
map.permalink '/a/:id', :controller => 'activities', :action => 'show_from_permalink'
map.faq '/faq', :controller => 'home', :action => 'faq'
map.about '/about', :controller => 'home', :action => 'faq'
+ map.privacy '/privacy', :controller => 'home', :action => 'privacy'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'OauthConsumers', :action => 'index'
map.root :controller => 'home', :action => 'index'
end
|
webcracy/activity_streams-workshop
|
0ce34aa28daaa0db1bec310afd49f0f912768948
|
added Streamed Authentication using Janrain Engage
|
diff --git a/app/controllers/oauth_consumers_controller.rb b/app/controllers/oauth_consumers_controller.rb
index 3218f87..8cc87c5 100644
--- a/app/controllers/oauth_consumers_controller.rb
+++ b/app/controllers/oauth_consumers_controller.rb
@@ -1,92 +1,92 @@
require 'oauth/controllers/consumer_controller'
class OauthConsumersController < ApplicationController
include Oauth::Controllers::ConsumerController
before_filter :load_consumer
skip_before_filter :login_required
def index
if logged_in?
@consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id}
@services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name}
end
end
# This callback method is heavily modified from the plugin's original to allow session and user creation
# from an Aidentiti Oauth Authorization
def callback
@request_token_secret = session[params[:oauth_token]]
if @request_token_secret
if params[:id] == 'aidentiti'
# Create an Aidentiti Oauth Consumer to grab the user's credential
@consumer = AidentitiToken.consumer
access_token = get_access_token(@consumer, params[:oauth_token], @request_token_secret, params[:oauth_verifier])
# Save the Consumer's token and use it to create the client
@token = AidentitiToken.create(:token => access_token.token, :secret => access_token.secret)
aidentiti_client = Aidentiti::Base.new(@token.client)
# Make the call to Aidentiti
user_profile = aidentiti_client.grab_credentials.user
# Do we need to create this user, or just load it?
user = User.find_or_create_by_email(:email => user_profile.email, :login => user_profile.login)
- user.password = user.password_confirmation = user.login.reverse
+ #user.password = user.password_confirmation = user.login.reverse
user.save
# Transfer any activities this user created as anonymous to the new found user
if session[:activities].present?
session[:activities].each do |a|
activity = Activity.find(a) rescue nil
activity.try(:update_attribute, :user_id, user.id)
end
session[:activities] = []
end
# Create a new session
reset_session
self.current_user = user
new_cookie_flag = true
handle_remember_cookie! new_cookie_flag
# Keep the Aidentiti Oauth Token table clean
old_consumer = AidentitiToken.find_by_user_id(user.id).delete if AidentitiToken.find_by_user_id(user.id)
# Wrap up by assigning the
@token.user_id = user.id
# elsif params[:id] == 'yammer'
# here you could use program specific behaviour for other oauth providers
end
if @token.save
flash[:notice] = "#{params[:id].humanize} was successfully connected to your account"
go_back
else
flash[:error] = "An error happened, please try connecting again"
redirect_to oauth_consumer_url(params[:id])
end
end
end
protected
# Change this to decide where you want to redirect user to after callback is finished.
# params[:id] holds the service name so you could use this to redirect to various parts
# of your application depending on what service you're connecting to.
def go_back
redirect_to root_url
end
def load_consumer
consumer_key=params[:id].to_sym
throw RecordNotFound unless OAUTH_CREDENTIALS.include?(consumer_key)
@consumer="#{consumer_key.to_s.camelcase}Token".constantize
if current_user
@[email protected]_by_user_id current_user.id
end
end
def get_access_token(consumer, token,secret,oauth_verifier)
request_token=OAuth::RequestToken.new consumer,token,secret
options={}
options[:oauth_verifier]=oauth_verifier if oauth_verifier
access_token=request_token.get_access_token options
access_token
end
end
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index deeba3b..e2ad4eb 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,44 +1,52 @@
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
- # Be sure to include AuthenticationSystem in Application Controller instead
- include AuthenticatedSystem
+ skip_before_filter :verify_authenticity_token, :only => [:rpx_token] # RPX does not pass Rails form tokens...
# render new.rhtml
def new
redirect_to oauth_consumers_path
end
def create
logout_keeping_session!
user = User.authenticate(params[:login], params[:password])
if user
# Protects against session fixation attacks, causes request forgery
# protection if user resubmits an earlier form using back
# button. Uncomment if you understand the tradeoffs.
# reset_session
self.current_user = user
new_cookie_flag = (params[:remember_me] == "1")
handle_remember_cookie! new_cookie_flag
redirect_back_or_default('/')
flash[:notice] = "Logged in successfully"
else
note_failed_signin
@login = params[:login]
@remember_me = params[:remember_me]
render :action => 'new'
end
end
def destroy
logout_killing_session!
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
+
+ # user_data
+ # found: {:name=>'John Doe', :username => 'john', :email=>'[email protected]', :identifier=>'blug.google.com/openid/dsdfsdfs3f3'}
+ # not found: nil (can happen with e.g. invalid tokens)
+ def rpx_token
+ raise "hackers?" unless data = RPXNow.user_data(params[:token])
+ self.current_user = User.find_by_email(data[:email]) || User.create!(data)
+ redirect_to '/'
+ end
protected
# Track failed login attempts
def note_failed_signin
flash[:error] = "Couldn't log you in as '#{params[:login]}'"
logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}"
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index caf6dda..57139d0 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,54 +1,54 @@
require 'digest/sha1'
class User < ActiveRecord::Base
include Authentication
- include Authentication::ByPassword
+ #include Authentication::ByPassword
include Authentication::ByCookieToken
- validates_presence_of :login
- validates_length_of :login, :within => 3..40
- validates_uniqueness_of :login
- validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
+ # validates_presence_of :login
+ # validates_length_of :login, :within => 3..40
+ # validates_uniqueness_of :login
+ # validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message
validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true
validates_length_of :name, :maximum => 100
validates_presence_of :email
validates_length_of :email, :within => 6..100 #[email protected]
validates_uniqueness_of :email
validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message
has_many :activities, :dependent => :destroy
# HACK HACK HACK -- how to do attr_accessible from here?
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :name, :password, :password_confirmation
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
#
# uff. this is really an authorization, not authentication routine.
# We really need a Dispatch Chain here or something.
# This will also let us return a human error message.
#
def self.authenticate(login, password)
return nil if login.blank? || password.blank?
u = find_by_login(login.downcase) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
def login=(value)
write_attribute :login, (value ? value.downcase : nil)
end
def email=(value)
write_attribute :email, (value ? value.downcase : nil)
end
protected
end
diff --git a/app/views/oauth_consumers/index.html.haml b/app/views/oauth_consumers/index.html.haml
index 1e32c35..7662b0d 100644
--- a/app/views/oauth_consumers/index.html.haml
+++ b/app/views/oauth_consumers/index.html.haml
@@ -1,28 +1,28 @@
%h1 Services
-
-
-if @consumer_tokens and @services
-if @consumer_tokens.empty?
%p
You are currently not connected to any external services.
-else
%p You are connected to the following services:
%ul
-@consumer_tokens.each do |token|
%li
=link_to token.class.service_name.to_s.humanize, oauth_consumer_path(token.class.service_name)
-if current_user
%br
%span= "You are authenticated as #{current_user.email}"
-unless @services.empty?
%h3 You can connect to the following services:
%ul
[email protected] do |service|
%li
=link_to service.to_s.humanize,oauth_consumer_path(service)
-else
%h3 Authenticate with Aidentiti
%p
- =link_to "Authenticate with Aidentiti", '/oauth_consumers/aidentiti'
\ No newline at end of file
+ =link_to "Authenticate with Aidentiti", '/oauth_consumers/aidentiti'
+
+ =RPXNow.embed_code('asws', url_for(:controller=>:sessions, :action=>:rpx_token, :default_provider=>'openid', :only_path => false))
diff --git a/config/environment.rb b/config/environment.rb
index 20532fb..b48ba7b 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,49 +1,54 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem 'haml'
config.gem 'oauth'
config.gem 'oauth-plugin'
config.gem 'mash', :lib => nil
config.gem 'httparty', :lib => nil
config.gem 'json'
config.gem 'coderay'
config.gem 'builder'
+ config.gem 'rpx_now'
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
+ config.after_initialize do # so rake gems:install works
+ RPXNow.api_key = "046934cbefdcbba00143f3499e89d274f913ec79"
+ end
+
end
diff --git a/config/routes.rb b/config/routes.rb
index 4afbba9..c373565 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,15 +1,15 @@
ActionController::Routing::Routes.draw do |map|
map.resources :activities, :member => { :publish => :post }
map.resources :oauth_consumers,:member=>{:callback=>:get}
map.resources :users
- map.resource :session
+ map.resource :session, :member=>{:rpx_token => [:get, :post]}
map.permalink '/a/:id', :controller => 'activities', :action => 'show_from_permalink'
map.faq '/faq', :controller => 'home', :action => 'faq'
map.about '/about', :controller => 'home', :action => 'faq'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'OauthConsumers', :action => 'index'
map.root :controller => 'home', :action => 'index'
end
|
webcracy/activity_streams-workshop
|
c348d3e76572cdef670d966ab7499cb19c47ea45
|
tweaked the styles a little bit
|
diff --git a/app/models/activity.rb b/app/models/activity.rb
index 773c8b0..2dadeb4 100644
--- a/app/models/activity.rb
+++ b/app/models/activity.rb
@@ -1,128 +1,132 @@
class Activity < ActiveRecord::Base
include ActionView::Helpers
include ActionController::UrlWriter
default_url_options[:host] = APP_CONFIG[:domain]
attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang
attr_accessible :actor_attributes, :target_attributes, :object_attributes
has_many :activity_objects, :dependent => :destroy
has_one :actor
has_one :object, :class_name => 'Obj'
has_one :target
belongs_to :user
named_scope :reverse, :order => 'created_at DESC'
named_scope :are_public, :conditions => {:is_public => true}
validates_presence_of :actor
validates_presence_of :verb
validates_presence_of :object
validates_presence_of :published_at
validates_presence_of :public_name, :if => Proc.new { |a| a.is_public }
before_create :add_permalink
accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? }
def self.verbs_to_select
[
['POST', "http://activitystrea.ms/schema/1.0/post"],
['FAVORITE', "http://activitystrea.ms/schema/1.0/favorite"],
['FOLLOW', 'http://activitystrea.ms/schema/1.0/follow'],
['LIKE', 'http://activitystrea.ms/schema/1.0/like'],
['MAKE-FRIEND', 'http://activitystrea.ms/schema/1.0/make-friend'],
['JOIN', 'http://activitystrea.ms/schema/1.0/join'],
['PLAY', 'http://activitystrea.ms/schema/1.0/play'],
['SAVE', 'http://activitystrea.ms/schema/1.0/save'],
['SHARE', 'http://activitystrea.ms/schema/1.0/share'],
['TAG', 'http://activitystrea.ms/schema/1.0/tag'],
['UPDATE', 'http://activitystrea.ms/schema/1.0/update']
]
end
+ def verb_title
+ verb.split('/').last.upcase
+ end
+
def to_json
a = {
:id => activity_url(self),
:permalinkUrl => activity_url(self),
:title => self.title,
:summary => self.summary,
:postedTime => self.published_at.to_s(:w3cdtf),
:actor => {
:id => self.actor.url_id,
:title => self.actor.title,
},
:object => {
:id => self.object.url_id,
:title => self.object.title,
- :objectType => self.object.object_type
+ :objectType => self.object.object_type
}
}
if self.target.present?
a[:target] = {
:id => self.target.url_id,
:title => self.target.title,
:objectType => self.target.object_type
}
end
return JSON.pretty_generate({
:data => {
:lang => "en-US",
:id => self.id,
:items => [ a ]
}
}.stringify_keys)
end
def to_xml
builder = Builder::XmlMarkup.new(:indent => 2)
builder.entry do |b|
b.id activity_url(self)
b.permalink activity_url(self)
b.published self.published_at.to_s(:w3cdtf)
b.title self.title
b.summary self.summary
b.author do
b.id self.actor.url_id
b.title self.actor.title
end
b.activity :verb, self.verb
b.activity :actor do
b.id self.actor.url_id
b.title self.actor.title, :type => 'text'
end
b.activity :object do
b.id self.object.url_id
b.title self.object.title, :type => 'text'
b.activity :"object-type", self.object.object_type
end
if self.target.present?
b.activity :target do
b.id self.target.url_id
b.title self.target.title, :type => 'text'
b.activity :"object-type", self.target.object_type
end
end
end
end
def add_permalink
hash = hash_gen(self)
while Activity.find_by_permalink(hash)
self.add_permalink
end
self.permalink = hash
end
private
def hash_gen(activity)
return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s
end
end
diff --git a/app/views/activities/_activity.html.haml b/app/views/activities/_activity.html.haml
index 2bc8130..9423f91 100644
--- a/app/views/activities/_activity.html.haml
+++ b/app/views/activities/_activity.html.haml
@@ -1,30 +1,43 @@
- content_tag_for :div, activity do
- - link_to activity.actor.url_id do
- = activity.actor.title.present? ? activity.actor.title : activity.actor.url_id
-
- %abbr{:title => activity.verb}= activity.verb.split('/').last.upcase
+ %abbr{:title => activity.actor.url_id}= activity.actor.title.present? ? activity.actor.title.upcase : activity.actor.url_id
+ %abbr{:title => activity.verb}= activity.verb_title
a
%abbr{:title => activity.object.object_type }= activity.object.object_type.split('/').last.upcase
- if activity.target.present?
in
%abbr{:title => activity.target.object_type}= activity.target.object_type.split('/').last.upcase
= time_ago_in_words activity.published_at
ago
= link_to '(activity permalink)', permalink_path(activity.permalink)
+
+ .object
+ .left.object_type
+ Actor
+ .linked-object.round
+ - link_to activity.actor.url_id do
+ = activity.actor.title.present? ? activity.actor.title : activity.actor.url_id
+
+ .object
+ .left.object_type
+ Verb
+ .linked-object.round
+ - link_to activity.verb do
+ = activity.verb_title
+
.object
.left.object_type
Object
.linked-object.round
- link_to activity.object.url_id do
= activity.object.title.present? ? activity.object.title : activity.object.url_id
- if activity.target.present?
.object
.left.target
Target
.linked-object.round
- link_to activity.target.url_id do
= activity.target.title.present? ? activity.target.title : activity.target.url_id
.clear
\ No newline at end of file
diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml
index f8d7af4..f85e9bb 100644
--- a/app/views/activities/show.html.haml
+++ b/app/views/activities/show.html.haml
@@ -1,38 +1,43 @@
- title "Activity"
%p.manage
= link_to "Permalink", permalink_path(@activity.permalink), :class => 'link'
-if logged_in? and @activity.user_id == current_user.id
|
= link_to "Edit", edit_activity_path(@activity), :class => 'edit'
|
= link_to "Destroy", @activity, :confirm => 'Are you sure?', :class => 'delete', :method => :delete
|
= link_to "Create another", new_activity_path, :class => 'new'
|
- = link_to_function "Submit as a public example", "jQuery('#submit_as_public_example').slideDown()", :id => 'submit_as_public_example_link', :class => 'submit'
+ - unless @activity.is_public?
+ = link_to_function "Submit as a public example", "jQuery('#submit_as_public_example').slideDown()", :id => 'submit_as_public_example_link', :class => 'submit'
+ - else
+ This is a public example activity
- if logged_in? and @activity.user_id == current_user.id
#submit_as_public_example{:style => 'display:none'}
- form_remote_tag :url => publish_activity_path(@activity), :html => { :class => 'hform largeform sticky' } do
#error_message
%p
= label :activity, :public_name
%span.hint.quiet Public title of this example
= text_field :activity, :public_name
= submit_tag "Publish"
#activity
=render :partial => 'activity', :locals => {:activity => @activity}
%h3 JSON
-~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class)
+.snippet
+ ~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class)
%h3 XML
-~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class)
+.snippet
+ ~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class)
%h3 FORM
= render :partial => 'form'
diff --git a/app/views/home/index.html.haml b/app/views/home/index.html.haml
index a3e9baa..8a866fb 100644
--- a/app/views/home/index.html.haml
+++ b/app/views/home/index.html.haml
@@ -1,24 +1,17 @@
- title "Welcome"
%p
- <strong>Activity Streams Workshop</strong> is a place to play and test with the
+ <strong>Activity Streams Workshop</strong> is a place to play with the
%a{:href => 'http://activitystrea.ms'} Activity Streams
format.
-
-%p It's a simple, hands-on, safe, free way to get acquainted with Activity Streams.
-
-%p Its creation was fueled by necessity and inspired by sites like <a href="http://pastebin.org" title="Pastebin">pastebin</a>, <a href="http://pastie.org" title="Pastie">pastie</a>, <a href="http://hurl.it" title="Hurl">hurl</a> or <a href="http://codepad.org" title="Codepad">codepad</a>.
%h2 Features
%ul
%li <a href="/activities" title="Browse Activities">Browse</a> valid Activity Streams examples
%li <a href="/activities/new" title="Create a new activity">Create</a> your own test Activity Streams with a simple form
- %li Consult, edit and share the JSON and Atom outputs
- %li Save your Activities (requires authentication with an Identity Provider such as OpenID, Google, Facebook, Twitter, etc.)
- %li (later) Post your activities to available Activity Streams APIs
%h2 Free Software
Activity Streams Workshop is built with <a href="http://rubyonrails.org" title="Ruby on Rails">Ruby on Rails</a> and you can <a href="http://github.com/webcracy/activity_streams-workshop" title="Activity Streams Workshop on Github">fork it on Github</a>.
\ No newline at end of file
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 7d75731..5000199 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,45 +1,45 @@
!!! Strict
%html{html_attrs}
%head
%title
= h(yield(:title).to_s + ' - Activity Streams Workshop')
- %meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
+ %meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}
%meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
%meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
#page
#header
#top
%h1{:style => 'float: left;'} Activity Streams Workshop
#user_bar{:style => 'float: right; text-align: right; '}
= render :partial => 'users/user_bar'
.clear
#nav
%ul.nav
%li
%a{:href => '/'} Home
%li
%a{:href => '/activities/new'} New activity
%li
%a{:href => '/activities'} Browse Activities
%li
%a{:href => '/faq'} FAQ
.clear
#content
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
- if show_title?
%h2=h yield(:title)
= yield
#footer
%p
Check out the <a href="http://activitystrea.ms" title="Activity Streams Website">Activity Streams</a> website. Grab the app's <a href="http://github.com/webcracy/activity_streams-workshop" title="Activity Streams Workshop code on Github">code</a>.
Please report any <a href="http://github.com/webcracy/activity_streams-workshop/issues" title="Activity Streams Workshop issues on Github">issues</a>.
%br
Created by <a href="http://0x82.com" title="Ruben Fonseca">Ruben Fonseca</a> and <a href="http://webcracy.org" title="Webcracy.org">Alex Solleiro</a> in 2010.
\ No newline at end of file
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index d1ea948..c6091e6 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,297 +1,311 @@
body {
margin: 0;
background-color: #4b7399;
font-family: 'Lucida Grande', Tahoma, Verdana, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
border: none;
}
.clear {
clear: both;
height: 0;
overflow: hidden;
}
.link {
font-size: 12px;
background:url('/images/link.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.delete {
font-size: 12px;
background:url('/images/delete.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.edit {
font-size: 12px;
background:url('/images/pencil.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.new {
font-size: 12px;
background:url('/images/add.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
.round {
-webkit-border-radius:2px;
-moz-border-radius:2px;
border-radius: 2px;
}
#page {
width: 900px;
margin: 0 auto;
background: white;
padding: 0px 20px;
/* border: solid 1px black;*/
}
#header {
padding-bottom: 20px;
border-bottom: 1px dotted black;
}
#header h1 {
margin: 15px 0px;
}
ul.nav{
padding: 0;
margin: 0;
width: 100%;
list-style: none;
}
ul.nav li {
float: left;
margin-right: 20px;
}
ul.nav li a {
color: black;
font-size: 16px;
}
#footer {
width: 60%;
margin: 30px auto;
text-align: center;
padding: 100px 0 20px 0;
}
#footer p {
color: gray;
font-size: 10px;
padding-top: 5px;
border-top: 1px dotted gray;
}
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
#error_message {
display: none;
font-size: 0.8em;
padding: 2px 2px;
margin: 0;
background-color: #ffcccc;
border: solid 1px #cc6666;
}
.fieldWithErrors {
display: inline;
border: solid 2px #cc6666; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
/* ACTIVITY */
ul#activities {
list-style: none;
}
ul#activities li {
margin-bottom: 15px;
}
p.manage {
+ line-height: 1.5em;
margin: -40px 0 25px 100px;
}
p.manage.x-l-margin {
margin-left: 120px;
}
#activity {
margin: 50px 20px;
}
.activity {
- border-left: 2px solid gray;
+ box-shadow: 10px 10px 5px #888; padding: 5px 5px 5px 15px;
+ -moz-box-shadow: 10px 10px 5px #888; padding: 5px 5px 5px 15px;
+ -webkit-box-shadow: 10px 10px 5px #888; padding: 5px 5px 5px 15px;
padding-left: 10px;
+ background-color: #F3F3F3;
+ border-color: black;
+
}
.object {
width: 550px;
margin: 5px;
}
.object .left {
float: left;
+ width: 35px;
margin-top: 5px;
padding: 10px;
font-size: 12px;
}
.linked-object {
float:left;
margin: 5px 0 0 10px;
border: 1px dashed gray;
padding: 10px;
width: 450px;
font-size: 12px;
}
+.snippet {
+ width: 100%;
+ overflow: auto;
+}
+
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
- padding: 0px; }
+ padding: 0px;
+ overflow: auto;
+ }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
form.largeform.sticky {margin-left: 0 !important;}
|
webcracy/activity_streams-workshop
|
3b347f809ddccc7d34498ddfd4a17bb1dadaa8fe
|
Implemented share activity stream with public
|
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb
index 3ce3b88..212e585 100644
--- a/app/controllers/activities_controller.rb
+++ b/app/controllers/activities_controller.rb
@@ -1,82 +1,90 @@
class ActivitiesController < ApplicationController
before_filter :login_or_oauth_required, :except => [:index, :new, :create, :show_from_permalink]
def index
if logged_in?
@activities = current_user.activities.reverse
else
@activities = (session[:activities] || []).map { |a| Activity.find(a) rescue nil }.compact
end
@public_activities = Activity.reverse.are_public
end
def show
@activity = find_from_session_or_user(params[:id])
end
def show_from_permalink
@activity = Activity.find_by_permalink(params[:id])
render :action => 'show'
end
def new
@activity = Activity.new
end
def create
@activity = Activity.new(params[:activity])
@activity.user = current_user
if @activity.save
unless logged_in?
session[:activities] ||= []
session[:activities] << @activity.id
end
flash[:notice] = "Successfully created activity."
redirect_to @activity
else
render :action => 'new'
end
end
def edit
@activity = find_from_session_or_user(params[:id])
end
def update
@activity = find_from_session_or_user(params[:id])
@activity.user = current_user
if @activity.update_attributes(params[:activity])
flash[:notice] = "Successfully updated activity."
redirect_to @activity
else
render :action => 'edit'
end
end
+
+ def publish
+ @activity = find_from_session_or_user(params[:id])
+ @activity.is_public = true
+ @activity.public_name = params[:activity][:public_name] rescue nil
+
+ @activity.save
+ end
def destroy
@activity = find_from_session_or_user(params[:id])
@activity.destroy
flash[:notice] = "Successfully destroyed activity."
redirect_to activities_url
end
private
def find_from_session_or_user(id)
# if the user is logged in, find from owned activities...
if logged_in?
current_user.activities.find(id)
# ... otherwhise, search for the activity id on the session
else
if session[:activities].find(id.to_i).present?
Activity.find(params[:id])
else
# everything fails, so give back 404
raise ActiveRecord::RecordNotfound
end
end
end
end
diff --git a/app/models/activity.rb b/app/models/activity.rb
index ccfd107..773c8b0 100644
--- a/app/models/activity.rb
+++ b/app/models/activity.rb
@@ -1,127 +1,128 @@
class Activity < ActiveRecord::Base
include ActionView::Helpers
include ActionController::UrlWriter
default_url_options[:host] = APP_CONFIG[:domain]
attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang
attr_accessible :actor_attributes, :target_attributes, :object_attributes
has_many :activity_objects, :dependent => :destroy
has_one :actor
has_one :object, :class_name => 'Obj'
has_one :target
belongs_to :user
named_scope :reverse, :order => 'created_at DESC'
named_scope :are_public, :conditions => {:is_public => true}
validates_presence_of :actor
validates_presence_of :verb
validates_presence_of :object
validates_presence_of :published_at
+ validates_presence_of :public_name, :if => Proc.new { |a| a.is_public }
before_create :add_permalink
accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? }
def self.verbs_to_select
[
['POST', "http://activitystrea.ms/schema/1.0/post"],
['FAVORITE', "http://activitystrea.ms/schema/1.0/favorite"],
['FOLLOW', 'http://activitystrea.ms/schema/1.0/follow'],
['LIKE', 'http://activitystrea.ms/schema/1.0/like'],
['MAKE-FRIEND', 'http://activitystrea.ms/schema/1.0/make-friend'],
['JOIN', 'http://activitystrea.ms/schema/1.0/join'],
['PLAY', 'http://activitystrea.ms/schema/1.0/play'],
['SAVE', 'http://activitystrea.ms/schema/1.0/save'],
['SHARE', 'http://activitystrea.ms/schema/1.0/share'],
['TAG', 'http://activitystrea.ms/schema/1.0/tag'],
['UPDATE', 'http://activitystrea.ms/schema/1.0/update']
]
end
def to_json
a = {
:id => activity_url(self),
:permalinkUrl => activity_url(self),
:title => self.title,
:summary => self.summary,
:postedTime => self.published_at.to_s(:w3cdtf),
:actor => {
:id => self.actor.url_id,
:title => self.actor.title,
},
:object => {
:id => self.object.url_id,
:title => self.object.title,
:objectType => self.object.object_type
}
}
if self.target.present?
a[:target] = {
:id => self.target.url_id,
:title => self.target.title,
:objectType => self.target.object_type
}
end
return JSON.pretty_generate({
:data => {
:lang => "en-US",
:id => self.id,
:items => [ a ]
}
}.stringify_keys)
end
def to_xml
builder = Builder::XmlMarkup.new(:indent => 2)
builder.entry do |b|
b.id activity_url(self)
b.permalink activity_url(self)
b.published self.published_at.to_s(:w3cdtf)
b.title self.title
b.summary self.summary
b.author do
b.id self.actor.url_id
b.title self.actor.title
end
b.activity :verb, self.verb
b.activity :actor do
b.id self.actor.url_id
b.title self.actor.title, :type => 'text'
end
b.activity :object do
b.id self.object.url_id
b.title self.object.title, :type => 'text'
b.activity :"object-type", self.object.object_type
end
if self.target.present?
b.activity :target do
b.id self.target.url_id
b.title self.target.title, :type => 'text'
b.activity :"object-type", self.target.object_type
end
end
end
end
def add_permalink
hash = hash_gen(self)
while Activity.find_by_permalink(hash)
self.add_permalink
end
self.permalink = hash
end
private
def hash_gen(activity)
return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s
end
end
diff --git a/app/views/activities/publish.js.erb b/app/views/activities/publish.js.erb
new file mode 100644
index 0000000..61f94c6
--- /dev/null
+++ b/app/views/activities/publish.js.erb
@@ -0,0 +1,7 @@
+<% if @activity.valid? %>
+ $('#submit_as_public_example').html("Thank you!").effect("highlight", {}, 3000).delay(3000).fadeOut();
+ $('#submit_as_public_example_link').fadeOut();
+<% else %>
+ $('#activity_public_name').addClass('fieldWithErrors');
+ $('#error_message').html("<%= @activity.errors.full_messages.to_sentence %>").fadeIn();
+<% end %>
diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml
index 9d1ee55..f8d7af4 100644
--- a/app/views/activities/show.html.haml
+++ b/app/views/activities/show.html.haml
@@ -1,25 +1,38 @@
- title "Activity"
%p.manage
= link_to "Permalink", permalink_path(@activity.permalink), :class => 'link'
-if logged_in? and @activity.user_id == current_user.id
|
= link_to "Edit", edit_activity_path(@activity), :class => 'edit'
|
= link_to "Destroy", @activity, :confirm => 'Are you sure?', :class => 'delete', :method => :delete
|
= link_to "Create another", new_activity_path, :class => 'new'
+ |
+ = link_to_function "Submit as a public example", "jQuery('#submit_as_public_example').slideDown()", :id => 'submit_as_public_example_link', :class => 'submit'
+
+- if logged_in? and @activity.user_id == current_user.id
+ #submit_as_public_example{:style => 'display:none'}
+ - form_remote_tag :url => publish_activity_path(@activity), :html => { :class => 'hform largeform sticky' } do
+ #error_message
+
+ %p
+ = label :activity, :public_name
+ %span.hint.quiet Public title of this example
+ = text_field :activity, :public_name
+ = submit_tag "Publish"
#activity
=render :partial => 'activity', :locals => {:activity => @activity}
%h3 JSON
~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class)
%h3 XML
~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class)
%h3 FORM
= render :partial => 'form'
diff --git a/config/routes.rb b/config/routes.rb
index 2f0815e..4afbba9 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,14 +1,15 @@
ActionController::Routing::Routes.draw do |map|
- map.resources :activities
+ map.resources :activities, :member => { :publish => :post }
map.resources :oauth_consumers,:member=>{:callback=>:get}
map.resources :users
map.resource :session
map.permalink '/a/:id', :controller => 'activities', :action => 'show_from_permalink'
+
map.faq '/faq', :controller => 'home', :action => 'faq'
map.about '/about', :controller => 'home', :action => 'faq'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'OauthConsumers', :action => 'index'
map.root :controller => 'home', :action => 'index'
end
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index ee82218..d1ea948 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,287 +1,297 @@
body {
margin: 0;
background-color: #4b7399;
font-family: 'Lucida Grande', Tahoma, Verdana, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
border: none;
}
.clear {
clear: both;
height: 0;
overflow: hidden;
}
.link {
font-size: 12px;
background:url('/images/link.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.delete {
font-size: 12px;
background:url('/images/delete.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.edit {
font-size: 12px;
background:url('/images/pencil.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.new {
font-size: 12px;
background:url('/images/add.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
.round {
-webkit-border-radius:2px;
-moz-border-radius:2px;
border-radius: 2px;
}
#page {
width: 900px;
margin: 0 auto;
background: white;
padding: 0px 20px;
/* border: solid 1px black;*/
}
#header {
padding-bottom: 20px;
border-bottom: 1px dotted black;
}
#header h1 {
margin: 15px 0px;
}
ul.nav{
padding: 0;
margin: 0;
width: 100%;
list-style: none;
}
ul.nav li {
float: left;
margin-right: 20px;
}
ul.nav li a {
color: black;
font-size: 16px;
}
#footer {
width: 60%;
margin: 30px auto;
text-align: center;
padding: 100px 0 20px 0;
}
#footer p {
color: gray;
font-size: 10px;
padding-top: 5px;
border-top: 1px dotted gray;
}
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
+#error_message {
+ display: none;
+ font-size: 0.8em;
+ padding: 2px 2px;
+ margin: 0;
+ background-color: #ffcccc;
+ border: solid 1px #cc6666;
+}
+
.fieldWithErrors {
- display: inline; }
+ display: inline;
+ border: solid 2px #cc6666; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
/* ACTIVITY */
ul#activities {
list-style: none;
}
ul#activities li {
margin-bottom: 15px;
}
p.manage {
margin: -40px 0 25px 100px;
}
p.manage.x-l-margin {
margin-left: 120px;
}
#activity {
margin: 50px 20px;
}
.activity {
border-left: 2px solid gray;
padding-left: 10px;
}
.object {
width: 550px;
margin: 5px;
}
.object .left {
float: left;
margin-top: 5px;
padding: 10px;
font-size: 12px;
}
.linked-object {
float:left;
margin: 5px 0 0 10px;
border: 1px dashed gray;
padding: 10px;
width: 450px;
font-size: 12px;
}
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
padding: 0px; }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
-form.largeform.sticky {margin-left: 0 !important;}
\ No newline at end of file
+form.largeform.sticky {margin-left: 0 !important;}
|
webcracy/activity_streams-workshop
|
7da6eac5b0bc0596ec1f489a3e5b3c4982af0a5d
|
tidy the Activity#index view
|
diff --git a/app/views/activities/index.html.haml b/app/views/activities/index.html.haml
index 7e0a9ec..dfbae0e 100644
--- a/app/views/activities/index.html.haml
+++ b/app/views/activities/index.html.haml
@@ -1,23 +1,25 @@
- title "Activities"
%p.manage.x-l-margin= link_to "New Activity", new_activity_path, :class => 'new'
%h3 Example Activities
%ul#activities
- for activity in @public_activities
%li
= render :partial => 'activity', :locals => {:activity => activity}
%h3 Your Activities
%ul#activities
- unless logged_in?
- %p You can <a href="/login" title="Login">login</a> using an external Identity Provider to <strong>save your activities</strong>.
+ %p
+ You can #{link_to 'Login', login_path} using an external Identity Provider to <strong>save</strong> your activities
+
- else
- for activity in @activities
%li
= render :partial => 'activity', :locals => {:activity => activity}
|
webcracy/activity_streams-workshop
|
ba4d124ca081ef1a7218ce11c0a2b5464b8af0a3
|
Moved Activity#to_sentence to a helper where it belongs
|
diff --git a/app/helpers/activities_helper.rb b/app/helpers/activities_helper.rb
index 4e9784c..d38072f 100644
--- a/app/helpers/activities_helper.rb
+++ b/app/helpers/activities_helper.rb
@@ -1,2 +1,12 @@
module ActivitiesHelper
+ def activity_to_sentence(activity)
+ [
+ link_to(activity.object.title, activity_path(activity)),
+ "- #{time_ago_in_words published_at} ago",
+ content_tag(:br),
+ link_to(activity.actor.title, activity.actor.url_id),
+ "| #{activity.verb} |",
+ link_to(activity.object.object_type, activity.object.url_id)
+ ]
+ end
end
diff --git a/app/models/activity.rb b/app/models/activity.rb
index 47c5370..ccfd107 100644
--- a/app/models/activity.rb
+++ b/app/models/activity.rb
@@ -1,132 +1,127 @@
class Activity < ActiveRecord::Base
include ActionView::Helpers
include ActionController::UrlWriter
default_url_options[:host] = APP_CONFIG[:domain]
attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang
attr_accessible :actor_attributes, :target_attributes, :object_attributes
has_many :activity_objects, :dependent => :destroy
has_one :actor
has_one :object, :class_name => 'Obj'
has_one :target
belongs_to :user
named_scope :reverse, :order => 'created_at DESC'
named_scope :are_public, :conditions => {:is_public => true}
validates_presence_of :actor
validates_presence_of :verb
validates_presence_of :object
validates_presence_of :published_at
before_create :add_permalink
accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? }
def self.verbs_to_select
[
['POST', "http://activitystrea.ms/schema/1.0/post"],
['FAVORITE', "http://activitystrea.ms/schema/1.0/favorite"],
['FOLLOW', 'http://activitystrea.ms/schema/1.0/follow'],
['LIKE', 'http://activitystrea.ms/schema/1.0/like'],
['MAKE-FRIEND', 'http://activitystrea.ms/schema/1.0/make-friend'],
['JOIN', 'http://activitystrea.ms/schema/1.0/join'],
['PLAY', 'http://activitystrea.ms/schema/1.0/play'],
['SAVE', 'http://activitystrea.ms/schema/1.0/save'],
['SHARE', 'http://activitystrea.ms/schema/1.0/share'],
['TAG', 'http://activitystrea.ms/schema/1.0/tag'],
['UPDATE', 'http://activitystrea.ms/schema/1.0/update']
]
end
- def to_sentence
- msg = "<a href='/activities/#{self.id}'>#{self.object.title}</a> - #{time_ago_in_words published_at} ago<br/>"
- msg += "<a href='#{self.actor.url_id}'>#{self.actor.title}</a> | #{self.verb} | <a href='#{self.object.url_id}'>#{self.object.object_type}</a>"
- end
-
def to_json
a = {
:id => activity_url(self),
:permalinkUrl => activity_url(self),
:title => self.title,
:summary => self.summary,
:postedTime => self.published_at.to_s(:w3cdtf),
:actor => {
:id => self.actor.url_id,
:title => self.actor.title,
},
:object => {
:id => self.object.url_id,
:title => self.object.title,
:objectType => self.object.object_type
}
}
if self.target.present?
a[:target] = {
:id => self.target.url_id,
:title => self.target.title,
:objectType => self.target.object_type
}
end
return JSON.pretty_generate({
:data => {
:lang => "en-US",
:id => self.id,
:items => [ a ]
}
}.stringify_keys)
end
def to_xml
builder = Builder::XmlMarkup.new(:indent => 2)
builder.entry do |b|
b.id activity_url(self)
b.permalink activity_url(self)
b.published self.published_at.to_s(:w3cdtf)
b.title self.title
b.summary self.summary
b.author do
b.id self.actor.url_id
b.title self.actor.title
end
b.activity :verb, self.verb
b.activity :actor do
b.id self.actor.url_id
b.title self.actor.title, :type => 'text'
end
b.activity :object do
b.id self.object.url_id
b.title self.object.title, :type => 'text'
b.activity :"object-type", self.object.object_type
end
if self.target.present?
b.activity :target do
b.id self.target.url_id
b.title self.target.title, :type => 'text'
b.activity :"object-type", self.target.object_type
end
end
end
end
def add_permalink
hash = hash_gen(self)
while Activity.find_by_permalink(hash)
self.add_permalink
end
self.permalink = hash
end
private
def hash_gen(activity)
return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s
end
end
|
webcracy/activity_streams-workshop
|
e7f7df9b307ebc4ea20124e476d1bc13f292cab7
|
fixed problem with remember_token
|
diff --git a/lib/authenticated_system.rb b/lib/authenticated_system.rb
index f993adc..74d58d0 100644
--- a/lib/authenticated_system.rb
+++ b/lib/authenticated_system.rb
@@ -1,189 +1,192 @@
module AuthenticatedSystem
protected
# Returns true or false if the user is logged in.
# Preloads @current_user with the user model if they're logged in.
def logged_in?
!!current_user
end
# Accesses the current user from the session.
# Future calls avoid the database because nil is not equal to false.
def current_user
@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_user == false
end
# Store the given user id in the session.
def current_user=(new_user)
session[:user_id] = new_user ? new_user.id : nil
@current_user = new_user || false
end
# Check if the user is authorized
#
# Override this method in your controllers if you want to restrict access
# to only a few actions or if you want to check if the user
# has the correct rights.
#
# Example:
#
# # only allow nonbobs
# def authorized?
# current_user.login != "bob"
# end
#
def authorized?(action = action_name, resource = nil)
logged_in?
end
# Filter method to enforce a login requirement.
#
# To require logins for all actions, use this in your controllers:
#
# before_filter :login_required
#
# To require logins for specific actions, use this in your controllers:
#
# before_filter :login_required, :only => [ :edit, :update ]
#
# To skip this in a subclassed controller:
#
# skip_before_filter :login_required
#
def login_required
authorized? || access_denied
end
# Redirect as appropriate when an access request fails.
#
# The default action is to redirect to the login screen.
#
# Override this method in your controllers if you want to have special
# behavior in case the user is not authorized
# to access the requested action. For example, a popup window might
# simply close itself.
def access_denied
respond_to do |format|
format.html do
store_location
redirect_to new_session_path
end
# format.any doesn't work in rails version < http://dev.rubyonrails.org/changeset/8987
# Add any other API formats here. (Some browsers, notably IE6, send Accept: */* and trigger
# the 'format.any' block incorrectly. See http://bit.ly/ie6_borken or http://bit.ly/ie6_borken2
# for a workaround.)
format.any(:json, :xml) do
request_http_basic_authentication 'Web Password'
end
end
end
# Store the URI of the current request in the session.
#
# We can return to this location by calling #redirect_back_or_default.
def store_location
session[:return_to] = request.request_uri
end
# Redirect to the URI stored by the most recent store_location call or
# to the passed default. Set an appropriately modified
# after_filter :store_location, :only => [:index, :new, :show, :edit]
# for any controller you want to be bounce-backable.
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
# Inclusion hook to make #current_user and #logged_in?
# available as ActionView helper methods.
def self.included(base)
base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method
end
#
# Login
#
# Called from #current_user. First attempt to login by the user id stored in the session.
def login_from_session
self.current_user = User.find_by_id(session[:user_id]) if session[:user_id]
end
# Called from #current_user. Now, attempt to login by basic authentication information.
def login_from_basic_auth
authenticate_with_http_basic do |login, password|
self.current_user = User.authenticate(login, password)
end
end
#
# Logout
#
# Called from #current_user. Finaly, attempt to login by an expiring token in the cookie.
# for the paranoid: we _should_ be storing user_token = hash(cookie_token, request IP)
def login_from_cookie
- user = !cookies[:auth_token].blank? and User.find_by_remember_token(cookies[:auth_token])
+ if cookies[:auth_token].present?
+ user = User.find_by_remember_token(cookies[:auth_token])
+ end
+
if user && user.remember_token?
self.current_user = user
handle_remember_cookie! false # freshen cookie token (keeping date)
self.current_user
end
end
# This is ususally what you want; resetting the session willy-nilly wreaks
# havoc with forgery protection, and is only strictly necessary on login.
# However, **all session state variables should be unset here**.
def logout_keeping_session!
# Kill server-side auth cookie
@current_user.forget_me if @current_user.is_a? User
@current_user = false # not logged in, and don't do it for me
kill_remember_cookie! # Kill client-side auth cookie
session[:user_id] = nil # keeps the session but kill our variable
# explicitly kill any other session variables you set
end
# The session should only be reset at the tail end of a form POST --
# otherwise the request forgery protection fails. It's only really necessary
# when you cross quarantine (logged-out to logged-in).
def logout_killing_session!
logout_keeping_session!
reset_session
end
#
# Remember_me Tokens
#
# Cookies shouldn't be allowed to persist past their freshness date,
# and they should be changed at each login
# Cookies shouldn't be allowed to persist past their freshness date,
# and they should be changed at each login
def valid_remember_cookie?
return nil unless @current_user
(@current_user.remember_token?) &&
(cookies[:auth_token] == @current_user.remember_token)
end
# Refresh the cookie auth token if it exists, create it otherwise
def handle_remember_cookie!(new_cookie_flag)
return unless @current_user
case
when valid_remember_cookie? then @current_user.refresh_token # keeping same expiry date
when new_cookie_flag then @current_user.remember_me
else @current_user.forget_me
end
send_remember_cookie!
end
def kill_remember_cookie!
cookies.delete :auth_token
end
def send_remember_cookie!
cookies[:auth_token] = {
:value => @current_user.remember_token,
:expires => @current_user.remember_token_expires_at }
end
end
|
webcracy/activity_streams-workshop
|
10900989db7eb4d5669b12f381e1e3489188c046
|
started to implement the example activites / your activities separation
|
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb
index 24f9689..3ce3b88 100644
--- a/app/controllers/activities_controller.rb
+++ b/app/controllers/activities_controller.rb
@@ -1,82 +1,82 @@
class ActivitiesController < ApplicationController
before_filter :login_or_oauth_required, :except => [:index, :new, :create, :show_from_permalink]
def index
if logged_in?
@activities = current_user.activities.reverse
else
@activities = (session[:activities] || []).map { |a| Activity.find(a) rescue nil }.compact
- Activity.find(:all, :conditions => {:is_public => true}).reverse.map{|a| @activities << a}
end
+ @public_activities = Activity.reverse.are_public
end
def show
@activity = find_from_session_or_user(params[:id])
end
def show_from_permalink
@activity = Activity.find_by_permalink(params[:id])
render :action => 'show'
end
def new
@activity = Activity.new
end
def create
@activity = Activity.new(params[:activity])
@activity.user = current_user
if @activity.save
unless logged_in?
session[:activities] ||= []
session[:activities] << @activity.id
end
flash[:notice] = "Successfully created activity."
redirect_to @activity
else
render :action => 'new'
end
end
def edit
@activity = find_from_session_or_user(params[:id])
end
def update
@activity = find_from_session_or_user(params[:id])
@activity.user = current_user
if @activity.update_attributes(params[:activity])
flash[:notice] = "Successfully updated activity."
redirect_to @activity
else
render :action => 'edit'
end
end
def destroy
@activity = find_from_session_or_user(params[:id])
@activity.destroy
flash[:notice] = "Successfully destroyed activity."
redirect_to activities_url
end
private
def find_from_session_or_user(id)
# if the user is logged in, find from owned activities...
if logged_in?
current_user.activities.find(id)
# ... otherwhise, search for the activity id on the session
else
if session[:activities].find(id.to_i).present?
Activity.find(params[:id])
else
# everything fails, so give back 404
raise ActiveRecord::RecordNotfound
end
end
end
end
diff --git a/app/models/activity.rb b/app/models/activity.rb
index 34395f9..47c5370 100644
--- a/app/models/activity.rb
+++ b/app/models/activity.rb
@@ -1,131 +1,132 @@
class Activity < ActiveRecord::Base
include ActionView::Helpers
include ActionController::UrlWriter
default_url_options[:host] = APP_CONFIG[:domain]
attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang
attr_accessible :actor_attributes, :target_attributes, :object_attributes
has_many :activity_objects, :dependent => :destroy
has_one :actor
has_one :object, :class_name => 'Obj'
has_one :target
belongs_to :user
named_scope :reverse, :order => 'created_at DESC'
+ named_scope :are_public, :conditions => {:is_public => true}
validates_presence_of :actor
validates_presence_of :verb
validates_presence_of :object
validates_presence_of :published_at
before_create :add_permalink
accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? }
def self.verbs_to_select
[
['POST', "http://activitystrea.ms/schema/1.0/post"],
['FAVORITE', "http://activitystrea.ms/schema/1.0/favorite"],
['FOLLOW', 'http://activitystrea.ms/schema/1.0/follow'],
['LIKE', 'http://activitystrea.ms/schema/1.0/like'],
['MAKE-FRIEND', 'http://activitystrea.ms/schema/1.0/make-friend'],
['JOIN', 'http://activitystrea.ms/schema/1.0/join'],
['PLAY', 'http://activitystrea.ms/schema/1.0/play'],
['SAVE', 'http://activitystrea.ms/schema/1.0/save'],
['SHARE', 'http://activitystrea.ms/schema/1.0/share'],
['TAG', 'http://activitystrea.ms/schema/1.0/tag'],
['UPDATE', 'http://activitystrea.ms/schema/1.0/update']
]
end
def to_sentence
msg = "<a href='/activities/#{self.id}'>#{self.object.title}</a> - #{time_ago_in_words published_at} ago<br/>"
msg += "<a href='#{self.actor.url_id}'>#{self.actor.title}</a> | #{self.verb} | <a href='#{self.object.url_id}'>#{self.object.object_type}</a>"
end
def to_json
a = {
:id => activity_url(self),
:permalinkUrl => activity_url(self),
:title => self.title,
:summary => self.summary,
:postedTime => self.published_at.to_s(:w3cdtf),
:actor => {
:id => self.actor.url_id,
:title => self.actor.title,
},
:object => {
:id => self.object.url_id,
:title => self.object.title,
:objectType => self.object.object_type
}
}
if self.target.present?
a[:target] = {
:id => self.target.url_id,
:title => self.target.title,
:objectType => self.target.object_type
}
end
return JSON.pretty_generate({
:data => {
:lang => "en-US",
:id => self.id,
:items => [ a ]
}
}.stringify_keys)
end
def to_xml
builder = Builder::XmlMarkup.new(:indent => 2)
builder.entry do |b|
b.id activity_url(self)
b.permalink activity_url(self)
b.published self.published_at.to_s(:w3cdtf)
b.title self.title
b.summary self.summary
b.author do
b.id self.actor.url_id
b.title self.actor.title
end
b.activity :verb, self.verb
b.activity :actor do
b.id self.actor.url_id
b.title self.actor.title, :type => 'text'
end
b.activity :object do
b.id self.object.url_id
b.title self.object.title, :type => 'text'
b.activity :"object-type", self.object.object_type
end
if self.target.present?
b.activity :target do
b.id self.target.url_id
b.title self.target.title, :type => 'text'
b.activity :"object-type", self.target.object_type
end
end
end
end
def add_permalink
hash = hash_gen(self)
while Activity.find_by_permalink(hash)
self.add_permalink
end
self.permalink = hash
end
private
def hash_gen(activity)
return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s
end
end
diff --git a/app/views/activities/index.html.haml b/app/views/activities/index.html.haml
index 407d799..7e0a9ec 100644
--- a/app/views/activities/index.html.haml
+++ b/app/views/activities/index.html.haml
@@ -1,11 +1,23 @@
- title "Activities"
%p.manage.x-l-margin= link_to "New Activity", new_activity_path, :class => 'new'
+%h3 Example Activities
+
%ul#activities
- - for activity in @activities
+ - for activity in @public_activities
%li
= render :partial => 'activity', :locals => {:activity => activity}
+%h3 Your Activities
+
+%ul#activities
+ - unless logged_in?
+ %p You can <a href="/login" title="Login">login</a> using an external Identity Provider to <strong>save your activities</strong>.
+ - else
+ - for activity in @activities
+ %li
+ = render :partial => 'activity', :locals => {:activity => activity}
+
|
webcracy/activity_streams-workshop
|
d149aaf6dab336cf1a0532f487cb4d33ec1ebb24
|
restyled the activities some more
|
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb
index 0bc0853..24f9689 100644
--- a/app/controllers/activities_controller.rb
+++ b/app/controllers/activities_controller.rb
@@ -1,82 +1,82 @@
class ActivitiesController < ApplicationController
before_filter :login_or_oauth_required, :except => [:index, :new, :create, :show_from_permalink]
def index
if logged_in?
- @activities = current_user.activities
+ @activities = current_user.activities.reverse
else
@activities = (session[:activities] || []).map { |a| Activity.find(a) rescue nil }.compact
- Activity.find(:all, :conditions => {:is_public => true}).map{|a| @activities << a}
+ Activity.find(:all, :conditions => {:is_public => true}).reverse.map{|a| @activities << a}
end
end
def show
@activity = find_from_session_or_user(params[:id])
end
def show_from_permalink
@activity = Activity.find_by_permalink(params[:id])
render :action => 'show'
end
def new
@activity = Activity.new
end
def create
@activity = Activity.new(params[:activity])
@activity.user = current_user
if @activity.save
unless logged_in?
session[:activities] ||= []
session[:activities] << @activity.id
end
flash[:notice] = "Successfully created activity."
redirect_to @activity
else
render :action => 'new'
end
end
def edit
@activity = find_from_session_or_user(params[:id])
end
def update
@activity = find_from_session_or_user(params[:id])
@activity.user = current_user
if @activity.update_attributes(params[:activity])
flash[:notice] = "Successfully updated activity."
redirect_to @activity
else
render :action => 'edit'
end
end
def destroy
@activity = find_from_session_or_user(params[:id])
@activity.destroy
flash[:notice] = "Successfully destroyed activity."
redirect_to activities_url
end
private
def find_from_session_or_user(id)
# if the user is logged in, find from owned activities...
if logged_in?
current_user.activities.find(id)
# ... otherwhise, search for the activity id on the session
else
if session[:activities].find(id.to_i).present?
Activity.find(params[:id])
else
# everything fails, so give back 404
raise ActiveRecord::RecordNotfound
end
end
end
end
diff --git a/app/models/activity.rb b/app/models/activity.rb
index 9c6a23e..34395f9 100644
--- a/app/models/activity.rb
+++ b/app/models/activity.rb
@@ -1,129 +1,131 @@
class Activity < ActiveRecord::Base
include ActionView::Helpers
include ActionController::UrlWriter
default_url_options[:host] = APP_CONFIG[:domain]
attr_accessible :url_id, :published_at, :verb, :title, :summary, :lang
attr_accessible :actor_attributes, :target_attributes, :object_attributes
has_many :activity_objects, :dependent => :destroy
has_one :actor
has_one :object, :class_name => 'Obj'
has_one :target
belongs_to :user
+
+ named_scope :reverse, :order => 'created_at DESC'
validates_presence_of :actor
validates_presence_of :verb
validates_presence_of :object
validates_presence_of :published_at
before_create :add_permalink
accepts_nested_attributes_for :actor, :object, :target, :reject_if => proc { |p| p['url_id'].blank? }
def self.verbs_to_select
[
['POST', "http://activitystrea.ms/schema/1.0/post"],
['FAVORITE', "http://activitystrea.ms/schema/1.0/favorite"],
['FOLLOW', 'http://activitystrea.ms/schema/1.0/follow'],
['LIKE', 'http://activitystrea.ms/schema/1.0/like'],
['MAKE-FRIEND', 'http://activitystrea.ms/schema/1.0/make-friend'],
['JOIN', 'http://activitystrea.ms/schema/1.0/join'],
['PLAY', 'http://activitystrea.ms/schema/1.0/play'],
['SAVE', 'http://activitystrea.ms/schema/1.0/save'],
['SHARE', 'http://activitystrea.ms/schema/1.0/share'],
['TAG', 'http://activitystrea.ms/schema/1.0/tag'],
['UPDATE', 'http://activitystrea.ms/schema/1.0/update']
]
end
def to_sentence
msg = "<a href='/activities/#{self.id}'>#{self.object.title}</a> - #{time_ago_in_words published_at} ago<br/>"
msg += "<a href='#{self.actor.url_id}'>#{self.actor.title}</a> | #{self.verb} | <a href='#{self.object.url_id}'>#{self.object.object_type}</a>"
end
def to_json
a = {
:id => activity_url(self),
:permalinkUrl => activity_url(self),
:title => self.title,
:summary => self.summary,
:postedTime => self.published_at.to_s(:w3cdtf),
:actor => {
:id => self.actor.url_id,
:title => self.actor.title,
},
:object => {
:id => self.object.url_id,
:title => self.object.title,
:objectType => self.object.object_type
}
}
if self.target.present?
a[:target] = {
:id => self.target.url_id,
:title => self.target.title,
:objectType => self.target.object_type
}
end
return JSON.pretty_generate({
:data => {
:lang => "en-US",
:id => self.id,
:items => [ a ]
}
}.stringify_keys)
end
def to_xml
builder = Builder::XmlMarkup.new(:indent => 2)
builder.entry do |b|
b.id activity_url(self)
b.permalink activity_url(self)
b.published self.published_at.to_s(:w3cdtf)
b.title self.title
b.summary self.summary
b.author do
b.id self.actor.url_id
b.title self.actor.title
end
b.activity :verb, self.verb
b.activity :actor do
b.id self.actor.url_id
b.title self.actor.title, :type => 'text'
end
b.activity :object do
b.id self.object.url_id
b.title self.object.title, :type => 'text'
b.activity :"object-type", self.object.object_type
end
if self.target.present?
b.activity :target do
b.id self.target.url_id
b.title self.target.title, :type => 'text'
b.activity :"object-type", self.target.object_type
end
end
end
end
def add_permalink
hash = hash_gen(self)
while Activity.find_by_permalink(hash)
self.add_permalink
end
self.permalink = hash
end
private
def hash_gen(activity)
return Digest::SHA1.hexdigest(activity.verb.to_s+activity.title.to_s+activity.summary.to_s+Time.now.to_f.to_s).to_s
end
end
diff --git a/app/views/activities/_activity.html.haml b/app/views/activities/_activity.html.haml
index 22a05ba..2bc8130 100644
--- a/app/views/activities/_activity.html.haml
+++ b/app/views/activities/_activity.html.haml
@@ -1,22 +1,30 @@
-- link_to activity.actor.url_id do
- = activity.actor.title.present? ? activity.actor.title : activity.actor.url_id
-
-%abbr{:title => activity.verb}= activity.verb.split('/').last.upcase
-a
-%abbr{:title => activity.object.object_type }= activity.object.object_type.split('/').last.upcase
-- if activity.target.present?
- in
- %abbr{:title => activity.target.object_type}= activity.target.object_type.split('/').last.upcase
-= time_ago_in_words activity.published_at
-ago
+- content_tag_for :div, activity do
+ - link_to activity.actor.url_id do
+ = activity.actor.title.present? ? activity.actor.title : activity.actor.url_id
+
+ %abbr{:title => activity.verb}= activity.verb.split('/').last.upcase
+ a
+ %abbr{:title => activity.object.object_type }= activity.object.object_type.split('/').last.upcase
+ - if activity.target.present?
+ in
+ %abbr{:title => activity.target.object_type}= activity.target.object_type.split('/').last.upcase
+ = time_ago_in_words activity.published_at
+ ago
-= link_to '(activity permalink)', permalink_path(activity.permalink)
+ = link_to '(activity permalink)', permalink_path(activity.permalink)
-.linked-object.round
- - link_to activity.object.url_id do
- = activity.object.title.present? ? activity.object.title : activity.object.url_id
+ .object
+ .left.object_type
+ Object
+ .linked-object.round
+ - link_to activity.object.url_id do
+ = activity.object.title.present? ? activity.object.title : activity.object.url_id
-- if activity.target.present?
- .linked-object.round
- - link_to activity.target.url_id do
- = activity.target.title.present? ? activity.target.title : activity.target.url_id
+ - if activity.target.present?
+ .object
+ .left.target
+ Target
+ .linked-object.round
+ - link_to activity.target.url_id do
+ = activity.target.title.present? ? activity.target.title : activity.target.url_id
+ .clear
\ No newline at end of file
diff --git a/app/views/activities/_form.html.haml b/app/views/activities/_form.html.haml
index f25101f..1a58631 100644
--- a/app/views/activities/_form.html.haml
+++ b/app/views/activities/_form.html.haml
@@ -1,81 +1,82 @@
- form_for @activity, :html => {:class => 'hform largeform sticky '} do |f|
= f.error_messages
- f.fields_for :actor, @activity.actor || @activity.build_actor do |actor|
%fieldset
%legend Actor
%p
= actor.label :url_id, "Id", :class => "hint"
%span.hint.quiet An URL (documentation)
= actor.text_field :url_id
%p
= actor.label :title
%span.hint.quiet
A String (documentation)
= actor.text_field :title
%fieldset
%legend Verb
%p
= f.label :verb
%span.hint.quiet (documentation)
= f.select :verb, Activity.verbs_to_select
- f.fields_for :object, @activity.object || @activity.build_object do |object|
%fieldset
%legend Object
%p
= object.label :url_id, "Id"
%span.hint.quiet An URL (documentation)
= object.text_field :url_id
%p
= object.label :object_type
%span.hint.quiet (documentation)
= object.select :object_type, Obj.to_select
%p
= object.label :title
%span.hint.quiet A String (documentation)
= object.text_field :title
- f.fields_for :target, @activity.target || @activity.build_target do |target|
%fieldset
%legend Target
%p
= target.label :url_id, "Id"
%span.hint.quiet An URL (documentation)
= target.text_field :url_id
%p
= target.label :object_type
%span.hint.quiet (documentation)
= target.select :object_type, Target.to_select
%p
= target.label :title
%span.hint.quiet A String (documentation)
= target.text_field :title
%fieldset
%legend Activity
%p
= f.label :title
%span.hint.quiet HTML (documentation)
= f.text_field :title
%p
= f.label :summary
%span.hint.quiet HTML (documentation)
= f.text_area :summary
%p
= f.label :published_at
%span.hint.quiet (documentation)
= f.datetime_select :published_at, {}, :class => "compact"
- %p
- = f.submit
+ - if controller.action_name == 'new' or controller.action_name == 'edit'
+ %p
+ = f.submit
diff --git a/app/views/activities/index.html.haml b/app/views/activities/index.html.haml
index 5153d7a..407d799 100644
--- a/app/views/activities/index.html.haml
+++ b/app/views/activities/index.html.haml
@@ -1,11 +1,11 @@
- title "Activities"
+%p.manage.x-l-margin= link_to "New Activity", new_activity_path, :class => 'new'
+
%ul#activities
- for activity in @activities
%li
= render :partial => 'activity', :locals => {:activity => activity}
- %br
-
-%p= link_to "New Activity", new_activity_path
+
diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml
index 5d52076..9d1ee55 100644
--- a/app/views/activities/show.html.haml
+++ b/app/views/activities/show.html.haml
@@ -1,21 +1,25 @@
- title "Activity"
--if logged_in? and @activity.user_id == current_user.id
- %p.manage
- = link_to "Permalink", permalink_path(@activity.permalink), :class => 'link'
+
+%p.manage
+ = link_to "Permalink", permalink_path(@activity.permalink), :class => 'link'
+ -if logged_in? and @activity.user_id == current_user.id
|
= link_to "Edit", edit_activity_path(@activity), :class => 'edit'
|
= link_to "Destroy", @activity, :confirm => 'Are you sure?', :class => 'delete', :method => :delete
|
= link_to "Create another", new_activity_path, :class => 'new'
#activity
=render :partial => 'activity', :locals => {:activity => @activity}
%h3 JSON
~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class)
%h3 XML
~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class)
+%h3 FORM
+= render :partial => 'form'
+
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index 1df4e24..ee82218 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,265 +1,287 @@
body {
margin: 0;
background-color: #4b7399;
- font-family: Verdana, Helvetica, Arial;
+ font-family: 'Lucida Grande', Tahoma, Verdana, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
border: none;
}
.clear {
clear: both;
height: 0;
overflow: hidden;
}
.link {
font-size: 12px;
background:url('/images/link.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.delete {
font-size: 12px;
background:url('/images/delete.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.edit {
font-size: 12px;
background:url('/images/pencil.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.new {
font-size: 12px;
background:url('/images/add.png') no-repeat 0px 0px;
line-height: 14px;
padding: 0 0 0 18px;
}
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
.round {
-webkit-border-radius:2px;
-moz-border-radius:2px;
border-radius: 2px;
}
#page {
width: 900px;
margin: 0 auto;
background: white;
padding: 0px 20px;
/* border: solid 1px black;*/
}
#header {
padding-bottom: 20px;
border-bottom: 1px dotted black;
}
#header h1 {
margin: 15px 0px;
}
ul.nav{
padding: 0;
margin: 0;
width: 100%;
list-style: none;
}
ul.nav li {
float: left;
margin-right: 20px;
}
ul.nav li a {
color: black;
font-size: 16px;
}
#footer {
width: 60%;
margin: 30px auto;
text-align: center;
padding: 100px 0 20px 0;
}
#footer p {
color: gray;
font-size: 10px;
padding-top: 5px;
border-top: 1px dotted gray;
}
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
.fieldWithErrors {
display: inline; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
/* ACTIVITY */
ul#activities {
list-style: none;
}
ul#activities li {
margin-bottom: 15px;
}
p.manage {
margin: -40px 0 25px 100px;
}
+p.manage.x-l-margin {
+ margin-left: 120px;
+}
+
#activity {
- margin: 40px 20px;
+ margin: 50px 20px;
+}
+
+.activity {
+ border-left: 2px solid gray;
+ padding-left: 10px;
+}
+
+.object {
+ width: 550px;
+ margin: 5px;
+}
+
+.object .left {
+ float: left;
+ margin-top: 5px;
+ padding: 10px;
+ font-size: 12px;
}
.linked-object {
+ float:left;
margin: 5px 0 0 10px;
border: 1px dashed gray;
padding: 10px;
width: 450px;
font-size: 12px;
}
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
padding: 0px; }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
form.largeform.sticky {margin-left: 0 !important;}
\ No newline at end of file
|
webcracy/activity_streams-workshop
|
cb3d58c6966876977c4822cd7ea96dafc18fb7ac
|
edited activity page
|
diff --git a/app/views/activities/_activity.html.haml b/app/views/activities/_activity.html.haml
new file mode 100644
index 0000000..22a05ba
--- /dev/null
+++ b/app/views/activities/_activity.html.haml
@@ -0,0 +1,22 @@
+- link_to activity.actor.url_id do
+ = activity.actor.title.present? ? activity.actor.title : activity.actor.url_id
+
+%abbr{:title => activity.verb}= activity.verb.split('/').last.upcase
+a
+%abbr{:title => activity.object.object_type }= activity.object.object_type.split('/').last.upcase
+- if activity.target.present?
+ in
+ %abbr{:title => activity.target.object_type}= activity.target.object_type.split('/').last.upcase
+= time_ago_in_words activity.published_at
+ago
+
+= link_to '(activity permalink)', permalink_path(activity.permalink)
+
+.linked-object.round
+ - link_to activity.object.url_id do
+ = activity.object.title.present? ? activity.object.title : activity.object.url_id
+
+- if activity.target.present?
+ .linked-object.round
+ - link_to activity.target.url_id do
+ = activity.target.title.present? ? activity.target.title : activity.target.url_id
diff --git a/app/views/activities/index.html.haml b/app/views/activities/index.html.haml
index ca6a072..5153d7a 100644
--- a/app/views/activities/index.html.haml
+++ b/app/views/activities/index.html.haml
@@ -1,10 +1,11 @@
- title "Activities"
-- for activity in @activities
- %p
- = activity.to_sentence
- %br
- = link_to 'Permalink', permalink_path(activity.permalink)
+%ul#activities
+ - for activity in @activities
+ %li
+ = render :partial => 'activity', :locals => {:activity => activity}
+ %br
+
%p= link_to "New Activity", new_activity_path
diff --git a/app/views/activities/show.html.haml b/app/views/activities/show.html.haml
index 6e4a651..5d52076 100644
--- a/app/views/activities/show.html.haml
+++ b/app/views/activities/show.html.haml
@@ -1,33 +1,21 @@
- title "Activity"
-
-%p= link_to "Permalink", permalink_path(:id => @activity.permalink)
-
-%p
- - link_to @activity.actor.url_id do
- = @activity.actor.title.present? ? @activity.actor.title : @activity.actor.url_id
-
- %abbr{:title => @activity.verb}= @activity.verb.split('/').last.upcase
-
- - link_to @activity.object.url_id do
- = @activity.object.title.present? ? @activity.object.title : @activity.object.url_id
-
- - if @activity.target.present?
- - link_to @activity.target.url_id do
- = @activity.target.title.present? ? @activity.target.title : @activity.target.url_id
-
- = time_ago_in_words @activity.published_at
- ago
-
+-if logged_in? and @activity.user_id == current_user.id
+ %p.manage
+ = link_to "Permalink", permalink_path(@activity.permalink), :class => 'link'
+ |
+ = link_to "Edit", edit_activity_path(@activity), :class => 'edit'
+ |
+ = link_to "Destroy", @activity, :confirm => 'Are you sure?', :class => 'delete', :method => :delete
+ |
+ = link_to "Create another", new_activity_path, :class => 'new'
+
+#activity
+ =render :partial => 'activity', :locals => {:activity => @activity}
+
%h3 JSON
~ CodeRay.scan(@activity.to_json, 'json').div(:line_numbers => :table, :css => :class)
%h3 XML
~ CodeRay.scan(@activity.to_xml, 'xml').div(:line_numbers => :table, :css => :class)
-%p
- = link_to "Edit", edit_activity_path(@activity)
- |
- = link_to "Destroy", @activity, :confirm => 'Are you sure?', :method => :delete
- |
- = link_to "Create another", new_activity_path
diff --git a/public/images/add.png b/public/images/add.png
new file mode 100755
index 0000000..0ea124a
Binary files /dev/null and b/public/images/add.png differ
diff --git a/public/images/delete.png b/public/images/delete.png
new file mode 100755
index 0000000..08f2493
Binary files /dev/null and b/public/images/delete.png differ
diff --git a/public/images/link.png b/public/images/link.png
new file mode 100755
index 0000000..25eacb7
Binary files /dev/null and b/public/images/link.png differ
diff --git a/public/images/pencil.png b/public/images/pencil.png
new file mode 100755
index 0000000..0bfecd5
Binary files /dev/null and b/public/images/pencil.png differ
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index bbda2c4..1df4e24 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,213 +1,265 @@
body {
margin: 0;
background-color: #4b7399;
font-family: Verdana, Helvetica, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
border: none;
}
.clear {
clear: both;
height: 0;
overflow: hidden;
}
+
+.link {
+ font-size: 12px;
+ background:url('/images/link.png') no-repeat 0px 0px;
+ line-height: 14px;
+ padding: 0 0 0 18px;
+}
+.delete {
+ font-size: 12px;
+ background:url('/images/delete.png') no-repeat 0px 0px;
+ line-height: 14px;
+ padding: 0 0 0 18px;
+}
+.edit {
+ font-size: 12px;
+ background:url('/images/pencil.png') no-repeat 0px 0px;
+ line-height: 14px;
+ padding: 0 0 0 18px;
+}
+.new {
+ font-size: 12px;
+ background:url('/images/add.png') no-repeat 0px 0px;
+ line-height: 14px;
+ padding: 0 0 0 18px;
+}
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
.round {
-webkit-border-radius:2px;
-moz-border-radius:2px;
border-radius: 2px;
}
#page {
width: 900px;
margin: 0 auto;
background: white;
padding: 0px 20px;
/* border: solid 1px black;*/
}
#header {
padding-bottom: 20px;
border-bottom: 1px dotted black;
}
#header h1 {
margin: 15px 0px;
}
ul.nav{
padding: 0;
margin: 0;
width: 100%;
list-style: none;
}
ul.nav li {
float: left;
margin-right: 20px;
}
ul.nav li a {
color: black;
font-size: 16px;
}
#footer {
width: 60%;
margin: 30px auto;
text-align: center;
padding: 100px 0 20px 0;
}
#footer p {
color: gray;
font-size: 10px;
padding-top: 5px;
border-top: 1px dotted gray;
}
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
.fieldWithErrors {
display: inline; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
+
+/* ACTIVITY */
+
+ul#activities {
+ list-style: none;
+}
+
+ul#activities li {
+ margin-bottom: 15px;
+}
+
+p.manage {
+ margin: -40px 0 25px 100px;
+}
+
+#activity {
+ margin: 40px 20px;
+}
+
+.linked-object {
+ margin: 5px 0 0 10px;
+ border: 1px dashed gray;
+ padding: 10px;
+ width: 450px;
+ font-size: 12px;
+}
+
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
padding: 0px; }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
form.largeform.sticky {margin-left: 0 !important;}
\ No newline at end of file
|
webcracy/activity_streams-workshop
|
a08734de46e118adb2d887c0ded5b4b4db1573c3
|
added a footer and changed the styles again
|
diff --git a/app/views/home/index.html.haml b/app/views/home/index.html.haml
index b5c5019..a3e9baa 100644
--- a/app/views/home/index.html.haml
+++ b/app/views/home/index.html.haml
@@ -1,24 +1,24 @@
- title "Welcome"
%p
<strong>Activity Streams Workshop</strong> is a place to play and test with the
%a{:href => 'http://activitystrea.ms'} Activity Streams
format.
%p It's a simple, hands-on, safe, free way to get acquainted with Activity Streams.
-%p Its creation was fueled by necessity and inspired by sites like pastebin, pastie or codepad.
+%p Its creation was fueled by necessity and inspired by sites like <a href="http://pastebin.org" title="Pastebin">pastebin</a>, <a href="http://pastie.org" title="Pastie">pastie</a>, <a href="http://hurl.it" title="Hurl">hurl</a> or <a href="http://codepad.org" title="Codepad">codepad</a>.
%h2 Features
%ul
%li <a href="/activities" title="Browse Activities">Browse</a> valid Activity Streams examples
%li <a href="/activities/new" title="Create a new activity">Create</a> your own test Activity Streams with a simple form
%li Consult, edit and share the JSON and Atom outputs
%li Save your Activities (requires authentication with an Identity Provider such as OpenID, Google, Facebook, Twitter, etc.)
%li (later) Post your activities to available Activity Streams APIs
%h2 Free Software
Activity Streams Workshop is built with <a href="http://rubyonrails.org" title="Ruby on Rails">Ruby on Rails</a> and you can <a href="http://github.com/webcracy/activity_streams-workshop" title="Activity Streams Workshop on Github">fork it on Github</a>.
\ No newline at end of file
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 4847d8e..7d75731 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,38 +1,45 @@
!!! Strict
%html{html_attrs}
%head
%title
= h(yield(:title).to_s + ' - Activity Streams Workshop')
%meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
%meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
%meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
#page
#header
#top
%h1{:style => 'float: left;'} Activity Streams Workshop
#user_bar{:style => 'float: right; text-align: right; '}
= render :partial => 'users/user_bar'
.clear
#nav
%ul.nav
%li
%a{:href => '/'} Home
%li
%a{:href => '/activities/new'} New activity
%li
%a{:href => '/activities'} Browse Activities
%li
%a{:href => '/faq'} FAQ
.clear
#content
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
- if show_title?
%h2=h yield(:title)
= yield
+
+ #footer
+ %p
+ Check out the <a href="http://activitystrea.ms" title="Activity Streams Website">Activity Streams</a> website. Grab the app's <a href="http://github.com/webcracy/activity_streams-workshop" title="Activity Streams Workshop code on Github">code</a>.
+ Please report any <a href="http://github.com/webcracy/activity_streams-workshop/issues" title="Activity Streams Workshop issues on Github">issues</a>.
+ %br
+ Created by <a href="http://0x82.com" title="Ruben Fonseca">Ruben Fonseca</a> and <a href="http://webcracy.org" title="Webcracy.org">Alex Solleiro</a> in 2010.
\ No newline at end of file
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index 0877c28..bbda2c4 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,200 +1,213 @@
body {
margin: 0;
background-color: #4b7399;
font-family: Verdana, Helvetica, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
border: none;
}
.clear {
clear: both;
height: 0;
overflow: hidden;
}
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
.round {
-webkit-border-radius:2px;
-moz-border-radius:2px;
border-radius: 2px;
}
#page {
width: 900px;
- min-height: 500px;
margin: 0 auto;
background: white;
padding: 0px 20px;
/* border: solid 1px black;*/
}
#header {
padding-bottom: 20px;
border-bottom: 1px dotted black;
}
#header h1 {
margin: 15px 0px;
}
ul.nav{
padding: 0;
margin: 0;
width: 100%;
list-style: none;
}
ul.nav li {
float: left;
margin-right: 20px;
}
ul.nav li a {
color: black;
font-size: 16px;
}
+#footer {
+ width: 60%;
+ margin: 30px auto;
+ text-align: center;
+ padding: 100px 0 20px 0;
+}
+
+#footer p {
+ color: gray;
+ font-size: 10px;
+ padding-top: 5px;
+ border-top: 1px dotted gray;
+}
+
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
.fieldWithErrors {
display: inline; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
padding: 0px; }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
form.largeform.sticky {margin-left: 0 !important;}
\ No newline at end of file
|
webcracy/activity_streams-workshop
|
5eea4f3acc10c63c4ba058604d560044e8608a14
|
changed the name of a couple css classes and html element ids
|
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 88ce82d..4847d8e 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,38 +1,38 @@
!!! Strict
%html{html_attrs}
%head
%title
= h(yield(:title).to_s + ' - Activity Streams Workshop')
%meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
%meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
%meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
#page
#header
#top
%h1{:style => 'float: left;'} Activity Streams Workshop
#user_bar{:style => 'float: right; text-align: right; '}
= render :partial => 'users/user_bar'
.clear
#nav
%ul.nav
- %li.round
+ %li
%a{:href => '/'} Home
- %li.round
+ %li
%a{:href => '/activities/new'} New activity
- %li.round
+ %li
%a{:href => '/activities'} Browse Activities
- %li.round
+ %li
%a{:href => '/faq'} FAQ
.clear
- #body
+ #content
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
- if show_title?
%h2=h yield(:title)
= yield
|
webcracy/activity_streams-workshop
|
2e76faabf44d8b860718194d9195ae033fd66db3
|
edited styles a little further
|
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index d0d4791..88ce82d 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,34 +1,38 @@
!!! Strict
%html{html_attrs}
%head
%title
- = h(yield(:title) + ' - Activity Streams Workshop' || "Activity Streams Workshop")
+ = h(yield(:title).to_s + ' - Activity Streams Workshop')
%meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
%meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
%meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
#page
- #user_bar{:style => 'text-align: right; width: 100%;'}
- = render :partial => 'users/user_bar'
- #nav
- %ul.nav
- %li.round
- %a{:href => '/'} Home
- %li.round
- %a{:href => '/activities/new'} New activity
- %li.round
- %a{:href => '/activities'} Browse Activities
- %li.round
- %a{:href => '/faq'} FAQ
- .clear
- - flash.each do |name, msg|
- = content_tag :div, msg, :id => "flash_#{name}"
+ #header
+ #top
+ %h1{:style => 'float: left;'} Activity Streams Workshop
+ #user_bar{:style => 'float: right; text-align: right; '}
+ = render :partial => 'users/user_bar'
+ .clear
+ #nav
+ %ul.nav
+ %li.round
+ %a{:href => '/'} Home
+ %li.round
+ %a{:href => '/activities/new'} New activity
+ %li.round
+ %a{:href => '/activities'} Browse Activities
+ %li.round
+ %a{:href => '/faq'} FAQ
+ .clear
#body
+ - flash.each do |name, msg|
+ = content_tag :div, msg, :id => "flash_#{name}"
- if show_title?
- %h1=h yield(:title)
+ %h2=h yield(:title)
= yield
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index 58bb68e..0877c28 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,192 +1,200 @@
body {
+ margin: 0;
background-color: #4b7399;
font-family: Verdana, Helvetica, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
- border: none; }
+ border: none;
+ }
.clear {
clear: both;
height: 0;
- overflow: hidden; }
+ overflow: hidden;
+}
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
.round {
-webkit-border-radius:2px;
-moz-border-radius:2px;
border-radius: 2px;
}
#page {
- width: 75%;
+ width: 900px;
+ min-height: 500px;
margin: 0 auto;
background: white;
- padding: 20px 40px;
- border: solid 1px black;
- margin-top: 20px; }
+ padding: 0px 20px;
+/* border: solid 1px black;*/
+}
+
+#header {
+ padding-bottom: 20px;
+ border-bottom: 1px dotted black;
+}
+
+#header h1 {
+ margin: 15px 0px;
+}
ul.nav{
padding: 0;
margin: 0;
width: 100%;
list-style: none;
}
ul.nav li {
float: left;
- padding: 7px 9px;
- background-color: darkblue;
margin-right: 20px;
- border-color: darkblue;
}
ul.nav li a {
- color: white;
+ color: black;
font-size: 16px;
- font-weight: normal;
- text-decoration: none;
}
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
.fieldWithErrors {
display: inline; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
padding: 0px; }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
form.largeform.sticky {margin-left: 0 !important;}
\ No newline at end of file
|
webcracy/activity_streams-workshop
|
242bbc6d755734b8f2b46253c4f2c372206bc382
|
created home controller and first drafts of home and faq pages
|
diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb
new file mode 100644
index 0000000..bfccb48
--- /dev/null
+++ b/app/controllers/home_controller.rb
@@ -0,0 +1,6 @@
+class HomeController < ApplicationController
+ def index
+ end
+ def faq
+ end
+end
diff --git a/app/helpers/home_helper.rb b/app/helpers/home_helper.rb
new file mode 100644
index 0000000..23de56a
--- /dev/null
+++ b/app/helpers/home_helper.rb
@@ -0,0 +1,2 @@
+module HomeHelper
+end
diff --git a/app/views/home/faq.html.haml b/app/views/home/faq.html.haml
new file mode 100644
index 0000000..e455bb7
--- /dev/null
+++ b/app/views/home/faq.html.haml
@@ -0,0 +1,5 @@
+-title "Frequently Asked Questions"
+
+%p
+ Activity Streams Workshop is a place to play and test with the Activity Streams format.
+
diff --git a/app/views/home/index.html.haml b/app/views/home/index.html.haml
new file mode 100644
index 0000000..b5c5019
--- /dev/null
+++ b/app/views/home/index.html.haml
@@ -0,0 +1,24 @@
+- title "Welcome"
+
+%p
+ <strong>Activity Streams Workshop</strong> is a place to play and test with the
+ %a{:href => 'http://activitystrea.ms'} Activity Streams
+ format.
+
+%p It's a simple, hands-on, safe, free way to get acquainted with Activity Streams.
+
+%p Its creation was fueled by necessity and inspired by sites like pastebin, pastie or codepad.
+
+%h2 Features
+
+%ul
+ %li <a href="/activities" title="Browse Activities">Browse</a> valid Activity Streams examples
+ %li <a href="/activities/new" title="Create a new activity">Create</a> your own test Activity Streams with a simple form
+ %li Consult, edit and share the JSON and Atom outputs
+ %li Save your Activities (requires authentication with an Identity Provider such as OpenID, Google, Facebook, Twitter, etc.)
+ %li (later) Post your activities to available Activity Streams APIs
+
+
+%h2 Free Software
+
+Activity Streams Workshop is built with <a href="http://rubyonrails.org" title="Ruby on Rails">Ruby on Rails</a> and you can <a href="http://github.com/webcracy/activity_streams-workshop" title="Activity Streams Workshop on Github">fork it on Github</a>.
\ No newline at end of file
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index b478de2..d0d4791 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,34 +1,34 @@
!!! Strict
%html{html_attrs}
%head
%title
= h(yield(:title) + ' - Activity Streams Workshop' || "Activity Streams Workshop")
%meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
%meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
%meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
#page
#user_bar{:style => 'text-align: right; width: 100%;'}
= render :partial => 'users/user_bar'
#nav
%ul.nav
%li.round
%a{:href => '/'} Home
%li.round
- %a{:href => '/'} New activity
+ %a{:href => '/activities/new'} New activity
%li.round
%a{:href => '/activities'} Browse Activities
%li.round
- %a{:href => '/about'} About
+ %a{:href => '/faq'} FAQ
.clear
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
#body
- if show_title?
%h1=h yield(:title)
= yield
diff --git a/config/routes.rb b/config/routes.rb
index e115a3e..2f0815e 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,12 +1,14 @@
ActionController::Routing::Routes.draw do |map|
map.resources :activities
map.resources :oauth_consumers,:member=>{:callback=>:get}
map.resources :users
map.resource :session
map.permalink '/a/:id', :controller => 'activities', :action => 'show_from_permalink'
+ map.faq '/faq', :controller => 'home', :action => 'faq'
+ map.about '/about', :controller => 'home', :action => 'faq'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'OauthConsumers', :action => 'index'
- map.root :controller => 'activities', :action => "new"
+ map.root :controller => 'home', :action => 'index'
end
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index eecd899..58bb68e 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,195 +1,192 @@
body {
background-color: #4b7399;
font-family: Verdana, Helvetica, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
border: none; }
.clear {
clear: both;
height: 0;
overflow: hidden; }
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
.round {
-webkit-border-radius:2px;
-moz-border-radius:2px;
border-radius: 2px;
}
#page {
width: 75%;
margin: 0 auto;
background: white;
padding: 20px 40px;
border: solid 1px black;
margin-top: 20px; }
-#nav {
- width: 100%;
-}
ul.nav{
padding: 0;
margin: 0;
width: 100%;
list-style: none;
}
ul.nav li {
float: left;
padding: 7px 9px;
background-color: darkblue;
margin-right: 20px;
border-color: darkblue;
}
ul.nav li a {
color: white;
font-size: 16px;
font-weight: normal;
text-decoration: none;
}
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
.fieldWithErrors {
display: inline; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
padding: 0px; }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
form.largeform.sticky {margin-left: 0 !important;}
\ No newline at end of file
diff --git a/test/functional/home_controller_test.rb b/test/functional/home_controller_test.rb
new file mode 100644
index 0000000..c205796
--- /dev/null
+++ b/test/functional/home_controller_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class HomeControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/test/unit/helpers/home_helper_test.rb b/test/unit/helpers/home_helper_test.rb
new file mode 100644
index 0000000..4740a18
--- /dev/null
+++ b/test/unit/helpers/home_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class HomeHelperTest < ActionView::TestCase
+end
|
webcracy/activity_streams-workshop
|
dc27db6c409b3cf877f1788a6dde4fac85c7a420
|
edited layout
|
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 96f5f8e..b478de2 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,34 +1,34 @@
!!! Strict
%html{html_attrs}
%head
%title
- = h(yield(:title) || "Activity Streams Workshop")
+ = h(yield(:title) + ' - Activity Streams Workshop' || "Activity Streams Workshop")
%meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
%meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
%meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
#page
#user_bar{:style => 'text-align: right; width: 100%;'}
= render :partial => 'users/user_bar'
#nav
%ul.nav
%li.round
%a{:href => '/'} Home
%li.round
%a{:href => '/'} New activity
%li.round
%a{:href => '/activities'} Browse Activities
%li.round
%a{:href => '/about'} About
.clear
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
#body
- if show_title?
%h1=h yield(:title)
= yield
|
webcracy/activity_streams-workshop
|
643e43e744567c854277b1bb1e77d51303ac18f5
|
added is_public and public_name fields to activities. require db:migrate. also added nav menu
|
diff --git a/app/controllers/activities_controller.rb b/app/controllers/activities_controller.rb
index 015df71..0bc0853 100644
--- a/app/controllers/activities_controller.rb
+++ b/app/controllers/activities_controller.rb
@@ -1,81 +1,82 @@
class ActivitiesController < ApplicationController
before_filter :login_or_oauth_required, :except => [:index, :new, :create, :show_from_permalink]
def index
if logged_in?
@activities = current_user.activities
else
@activities = (session[:activities] || []).map { |a| Activity.find(a) rescue nil }.compact
+ Activity.find(:all, :conditions => {:is_public => true}).map{|a| @activities << a}
end
end
def show
@activity = find_from_session_or_user(params[:id])
end
def show_from_permalink
@activity = Activity.find_by_permalink(params[:id])
render :action => 'show'
end
def new
@activity = Activity.new
end
def create
@activity = Activity.new(params[:activity])
@activity.user = current_user
if @activity.save
unless logged_in?
session[:activities] ||= []
session[:activities] << @activity.id
end
flash[:notice] = "Successfully created activity."
redirect_to @activity
else
render :action => 'new'
end
end
def edit
@activity = find_from_session_or_user(params[:id])
end
def update
@activity = find_from_session_or_user(params[:id])
@activity.user = current_user
if @activity.update_attributes(params[:activity])
flash[:notice] = "Successfully updated activity."
redirect_to @activity
else
render :action => 'edit'
end
end
def destroy
@activity = find_from_session_or_user(params[:id])
@activity.destroy
flash[:notice] = "Successfully destroyed activity."
redirect_to activities_url
end
private
def find_from_session_or_user(id)
# if the user is logged in, find from owned activities...
if logged_in?
current_user.activities.find(id)
# ... otherwhise, search for the activity id on the session
else
if session[:activities].find(id.to_i).present?
Activity.find(params[:id])
else
# everything fails, so give back 404
raise ActiveRecord::RecordNotfound
end
end
end
end
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index d02f0ee..96f5f8e 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,23 +1,34 @@
!!! Strict
%html{html_attrs}
-
%head
%title
= h(yield(:title) || "Activity Streams Workshop")
%meta{"http-equiv"=>"Content-Type", :content=>"text/html; charset=utf-8"}/
+ %meta{:name => "description", :content => "Activity Streams Workshop is a place to test and play with the Activity Streams format."}
+ %meta{:name => "keywords", :content => "activity streams, activities, format, schema, test, json, atom, ruby, rails"}
= stylesheet_link_tag 'application'
= javascript_include_tag :defaults
= yield(:head)
%body
- #container
+ #page
#user_bar{:style => 'text-align: right; width: 100%;'}
= render :partial => 'users/user_bar'
-
+ #nav
+ %ul.nav
+ %li.round
+ %a{:href => '/'} Home
+ %li.round
+ %a{:href => '/'} New activity
+ %li.round
+ %a{:href => '/activities'} Browse Activities
+ %li.round
+ %a{:href => '/about'} About
+ .clear
- flash.each do |name, msg|
= content_tag :div, msg, :id => "flash_#{name}"
+ #body
+ - if show_title?
+ %h1=h yield(:title)
- - if show_title?
- %h1=h yield(:title)
-
- = yield
+ = yield
diff --git a/db/migrate/20100721133530_add_is_public_and_public_name_to_activities.rb b/db/migrate/20100721133530_add_is_public_and_public_name_to_activities.rb
new file mode 100644
index 0000000..f3b492e
--- /dev/null
+++ b/db/migrate/20100721133530_add_is_public_and_public_name_to_activities.rb
@@ -0,0 +1,11 @@
+class AddIsPublicAndPublicNameToActivities < ActiveRecord::Migration
+ def self.up
+ add_column :activities, :is_public, :boolean
+ add_column :activities, :public_name, :string
+ end
+
+ def self.down
+ remove_column :activities, :public_name
+ remove_column :activities, :is_public
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index fe88121..11bfe9e 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,68 +1,70 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20100714110115) do
+ActiveRecord::Schema.define(:version => 20100721133530) do
create_table "activities", :force => true do |t|
t.integer "user_id"
t.string "url_id"
t.string "verb"
t.string "title"
t.text "summary"
t.string "lang"
t.datetime "published_at"
t.datetime "created_at"
t.datetime "updated_at"
t.string "permalink"
+ t.boolean "is_public"
+ t.string "public_name"
end
add_index "activities", ["user_id"], :name => "index_activities_on_user_id"
create_table "activity_objects", :force => true do |t|
t.integer "activity_id"
t.string "type"
t.string "url_id"
t.string "title"
t.datetime "published_at"
t.datetime "created_at"
t.datetime "updated_at"
t.string "object_type"
end
add_index "activity_objects", ["activity_id"], :name => "index_activity_objects_on_activity_id"
add_index "activity_objects", ["type"], :name => "index_activity_objects_on_type"
create_table "consumer_tokens", :force => true do |t|
t.integer "user_id"
t.string "type", :limit => 30
t.string "token", :limit => 1024
t.string "secret"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "consumer_tokens", ["token"], :name => "index_consumer_tokens_on_token", :unique => true
create_table "users", :force => true do |t|
t.string "login", :limit => 40
t.string "name", :limit => 100, :default => ""
t.string "email", :limit => 100
t.string "crypted_password", :limit => 40
t.string "salt", :limit => 40
t.datetime "created_at"
t.datetime "updated_at"
t.string "remember_token", :limit => 40
t.datetime "remember_token_expires_at"
end
add_index "users", ["login"], :name => "index_users_on_login", :unique => true
end
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index e0c51f7..eecd899 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -1,164 +1,195 @@
body {
background-color: #4b7399;
font-family: Verdana, Helvetica, Arial;
font-size: 14px; }
a {
color: blue; }
a img {
border: none; }
.clear {
clear: both;
height: 0;
overflow: hidden; }
.quiet {
text-decoration: none;
font-size: small;
color: gray;
}
-#container {
+.round {
+ -webkit-border-radius:2px;
+ -moz-border-radius:2px;
+ border-radius: 2px;
+}
+
+#page {
width: 75%;
margin: 0 auto;
background: white;
padding: 20px 40px;
border: solid 1px black;
margin-top: 20px; }
+#nav {
+ width: 100%;
+}
+ul.nav{
+ padding: 0;
+ margin: 0;
+ width: 100%;
+ list-style: none;
+}
+ul.nav li {
+ float: left;
+ padding: 7px 9px;
+ background-color: darkblue;
+ margin-right: 20px;
+ border-color: darkblue;
+}
+
+ul.nav li a {
+ color: white;
+ font-size: 16px;
+ font-weight: normal;
+ text-decoration: none;
+}
+
+
#flash_notice,
#flash_error {
padding: 5px 8px;
margin: 10px 0; }
#flash_notice {
background-color: #ccffcc;
border: solid 1px #66cc66; }
#flash_error {
background-color: #ffcccc;
border: solid 1px #cc6666; }
.fieldWithErrors {
display: inline; }
#errorExplanation {
width: 400px;
border: 2px solid #cf0000;
padding: 0;
padding-bottom: 12px;
margin-bottom: 20px;
background-color: #f0f0f0; }
#errorExplanation h2 {
text-align: left;
padding: 5px 5px 5px 15px;
margin: 0;
font-weight: bold;
font-size: 12px;
background-color: #cc0000;
color: white; }
#errorExplanation p {
color: #333333;
margin-bottom: 0;
padding: 8px; }
#errorExplanation ul {
margin: 2px 24px; }
#errorExplanation ul li {
font-size: 12px;
list-style: disc; }
.CodeRay {
background-color: #232323;
border: 1px solid black;
font-family: "Courier New", "Terminal", monospace;
color: #e6e0db;
padding: 3px 5px;
overflow: auto;
font-size: 12px;
margin: 12px 0; }
.CodeRay pre {
margin: 0px;
padding: 0px; }
.CodeRay .an {
color: #e7be69; }
.CodeRay .c {
color: #bc9358;
font-style: italic; }
.CodeRay .ch {
color: #509e4f; }
.CodeRay .cl {
color: white; }
.CodeRay .co {
color: white; }
.CodeRay .fl {
color: #a4c260; }
.CodeRay .fu {
color: #ffc56d; }
.CodeRay .gv {
color: #d0cffe; }
.CodeRay .i {
color: #a4c260; }
.CodeRay .il {
background: #151515; }
.CodeRay .iv {
color: #d0cffe; }
.CodeRay .pp {
color: #e7be69; }
.CodeRay .r {
color: #cb7832; }
.CodeRay .rx {
color: #a4c260; }
.CodeRay .s {
color: #a4c260; }
.CodeRay .sy {
color: #6c9cbd; }
.CodeRay .ta {
color: #e7be69; }
.CodeRay .pc {
color: #6c9cbd; }
/* hFORM */
form.hform p { margin-bottom: 10px; }
form.hform p label { float: left; width: 100px; }
form.hform p input { width: 200px; }
form.hform p select { width: 200px; }
form.hform p input.button { width: auto; }
form.hform p input.checkbox { width: auto; }
form.hform p input.radio { width: auto; }
form.hform p.checkbox { margin-left: 100px; }
form.hform p.checkbox label { float: none; }
form.hform p.checkbox input { width: auto; }
/* hFORM modification: largeform (forms that use this class should require hform first)*/
form.largeform {margin-left: 50px;}
form.largeform {width: 550px;}
form.largeform fieldset.outter {padding: 20px 0 0 30px;}
form.largeform legend.outter {font-size: 1.2em;}
form.largeform h3 { color:#AFAFAF; border-bottom:1px solid;font-size:18px;line-height:20px;margin:40px 0px 20px 0px; width:400px;}
form.largeform p { margin-bottom: 20px; }
form.largeform p label { float: left; width: 150px; }
form.largeform p input { width: 160px; }
form.largeform p.checkbox { margin-left: 150px; }
form.largeform p.compact_select { width: 100%; height: 30px; }
form.largeform p.action_hint { margin: -5px 0 5px 0; padding-left: 3px; background-color: #FFA; width: 300px;}
form.largeform p.submit {margin-top: 40px;}
form.largeform span.action_hint { line-height: 16px; font-size: 10px; height: 16px; padding: 2px 0 0 20px; text-transform: uppercase; font-weight: ; }
form.largeform span.action_hint.email { background: url('/images/email.png') no-repeat; }
form.largeform span.action_hint.twitter { background: url('/images/twitter_2.png') no-repeat; }
form.largeform span.compact_select { width: 200px; clear:both;}
form.largeform span.hint { clear: both; float: left; width: 145px; margin-right: 5px; line-height: 12px; font-size: 11px; }
form.largeform input[type="text"],
form.largeform input[type="password"] {
height: 1.6em; font-size: 1em; padding-left: 5px; width: 220px;
}
form.largeform input[type="text"].compact { padding-left: 2px; width: 35px;}
form.largeform select { height: 1.6em; line-height: 1.4em; font-size: 11px; padding-left: 5px;}
form.largeform select.compact { width:auto; padding-left: 1px;}
form.largeform div#inner_email.inner_fieldset {margin-bottom: 10px; }
form.largeform div.inner_fieldset {margin-left: 148px; padding-left: 2px; }
form.largeform div.inner_fieldset.actions { -webkit-border-radius:2px; -moz-border-radius:2px;}
form.largeform.sticky {margin-left: 0 !important;}
\ No newline at end of file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.