CCMain.m 258 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCOfflineFileFolder.h"
  27. #import <OCCommunicationLib/OCNotifications.h>
  28. #import <OCCommunicationLib/OCNotificationsAction.h>
  29. #import <OCCommunicationLib/OCFrameworkConstants.h>
  30. #import "Nextcloud-Swift.h"
  31. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  32. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  33. #define alertCreateFolder 1
  34. #define alertCreateFolderCrypto 2
  35. #define alertRename 3
  36. #define alertOfflineFolder 4
  37. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate>
  38. {
  39. CCMetadata *_metadataSegue;
  40. CCMetadata *_metadata;
  41. BOOL _isMain;
  42. BOOL _isViewDidLoad;
  43. BOOL _isOfflineServerUrl;
  44. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  45. BOOL _isSelectedMode;
  46. long _numTaskUploadInProgress;
  47. NSMutableArray *_selectedMetadatas;
  48. NSMutableArray *_queueSelector;
  49. NSUInteger _numSelectedMetadatas;
  50. UIImageView *_ImageTitleHomeCryptoCloud;
  51. UIView *_reMenuBackgroundView;
  52. UITapGestureRecognizer *_singleFingerTap;
  53. NSString *_directoryGroupBy;
  54. NSString *_directoryOrder;
  55. NSUInteger _failedAttempts;
  56. NSDate *_lockUntilDate;
  57. NSString *_fatherPermission;
  58. UIRefreshControl *_refreshControl;
  59. UIDocumentInteractionController *_docController;
  60. CCHud *_hud;
  61. CCHud *_hudDeterminate;
  62. // Datasource
  63. CCSectionDataSource *_sectionDataSource;
  64. NSDate *_dateReadDataSource;
  65. // Search
  66. BOOL _isSearchMode;
  67. NSString *_searchFileName;
  68. }
  69. @end
  70. @implementation CCMain
  71. #pragma --------------------------------------------------------------------------------------------
  72. #pragma mark ===== Init =====
  73. #pragma --------------------------------------------------------------------------------------------
  74. - (id)initWithCoder:(NSCoder *)aDecoder
  75. {
  76. if (self = [super initWithCoder:aDecoder]) {
  77. _directoryOrder = [CCUtility getOrderSettings];
  78. _directoryGroupBy = [CCUtility getGroupBySettings];
  79. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  80. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitleNOAnimation) name:@"setTitleCCMainNOAnimation" object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitleYESAnimation) name:@"setTitleCCMainYESAnimation" object:nil];
  83. }
  84. return self;
  85. }
  86. #pragma --------------------------------------------------------------------------------------------
  87. #pragma mark ===== View =====
  88. #pragma --------------------------------------------------------------------------------------------
  89. - (void)viewDidLoad
  90. {
  91. [super viewDidLoad];
  92. // init object
  93. //_actions = [CCActions new];
  94. _metadata = [[CCMetadata alloc] init];
  95. _metadataSegue = [[CCMetadata alloc] init];
  96. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  97. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  98. _selectedMetadatas = [[NSMutableArray alloc] init];
  99. _queueSelector = [[NSMutableArray alloc] init];
  100. _isViewDidLoad = YES;
  101. _fatherPermission = @"";
  102. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  103. // delegate
  104. self.tableView.delegate = self;
  105. self.tableView.tableFooterView = [UIView new];
  106. self.tableView.separatorColor = COLOR_SEPARATOR_TABLE;
  107. self.searchController.delegate = self;
  108. self.searchController.searchBar.delegate = self;
  109. [[CCNetworking sharedNetworking] settingDelegate:self];
  110. // Custom Cell
  111. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  112. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  113. // long press recognizer TableView
  114. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  115. [self.tableView addGestureRecognizer:longPressRecognizer];
  116. // Pull-to-Refresh
  117. [self createRefreshControl];
  118. // Register for 3D Touch Previewing if available
  119. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  120. {
  121. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  122. }
  123. // Back Button
  124. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl typeCloud:app.typeCloud]])
  125. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController] style:UIBarButtonItemStylePlain target:nil action:nil];
  126. // reMenu Background
  127. _reMenuBackgroundView = [[UIView alloc] init];
  128. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  129. // if this is not Main (the Main uses inizializeMain)
  130. if (_isMain == NO && app.activeAccount) {
  131. // Settings this folder & delegate & Loading datasource
  132. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  133. // Load Datasource
  134. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  135. // Read Folder
  136. [self readFolderWithForced:NO];
  137. }
  138. // Title
  139. [self setTitleNOAnimation];
  140. // List Transfers
  141. app.controlCenter = (CCControlCenter *)self.navigationController;
  142. // Search
  143. self.searchController.searchResultsUpdater = self;
  144. self.searchController.dimsBackgroundDuringPresentation = NO;
  145. self.tableView.tableHeaderView = self.searchController.searchBar;
  146. self.searchController.searchBar.scopeButtonTitles = @[NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil)];
  147. self.searchController.searchBar.barTintColor = COLOR_SEPARATOR_TABLE;
  148. [self.searchController.searchBar sizeToFit];
  149. }
  150. // Apparirà
  151. - (void)viewWillAppear:(BOOL)animated
  152. {
  153. [super viewWillAppear:animated];
  154. // Settings this folder & delegate & Loading datasource
  155. if (app.activeAccount) {
  156. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  157. }
  158. [[CCNetworking sharedNetworking] settingDelegate:self];
  159. // Color
  160. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  161. [CCAspect aspectTabBar:self.tabBarController.tabBar hidden:NO];
  162. // Menu e Bar
  163. [self createReMainMenu];
  164. [self createReSelectMenu];
  165. if (_isSelectedMode)
  166. [self setUINavigationBarSelected];
  167. else [self setUINavigationBarDefault];
  168. // Plus Button
  169. [app plusButtonVisibile:true];
  170. }
  171. // E' arrivato
  172. - (void)viewDidAppear:(BOOL)animated
  173. {
  174. [super viewDidAppear:animated];
  175. // Active Main
  176. app.activeMain = self;
  177. // Test viewDidLoad
  178. if (_isViewDidLoad) {
  179. _isViewDidLoad = NO;
  180. } else {
  181. if (app.activeAccount) {
  182. // Load Datasource
  183. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  184. // Read Folder
  185. [self readFolderWithForced:NO];
  186. }
  187. }
  188. // Title
  189. [self setTitle];
  190. // cancell Progress
  191. [self.navigationController cancelCCProgress];
  192. }
  193. - (void)viewWillDisappear:(BOOL)animated
  194. {
  195. [super viewWillDisappear:animated];
  196. // Close MainMenu & SelectMenu
  197. if (app.reMainMenu.isOpen || app.reSelectMenu.isOpen) {
  198. [app.reMainMenu close];
  199. [app.reSelectMenu close];
  200. }
  201. // Close Menu change user
  202. [CCMenu dismissMenu];
  203. }
  204. - (void)didReceiveMemoryWarning
  205. {
  206. [super didReceiveMemoryWarning];
  207. // Dispose of any resources that can be recreated.
  208. }
  209. - (BOOL)prefersStatusBarHidden
  210. {
  211. return NO;
  212. }
  213. #pragma --------------------------------------------------------------------------------------------
  214. #pragma mark ===== Initizlize Mail =====
  215. #pragma --------------------------------------------------------------------------------------------
  216. - (void)initializeMain:(NSNotification *)notification
  217. {
  218. _directoryGroupBy = nil;
  219. _directoryOrder = nil;
  220. _dateReadDataSource = nil;
  221. // test
  222. if ([app.activeAccount length] == 0 || [app.activeUrl length] == 0 || [app.typeCloud length] == 0)
  223. return;
  224. if ([app.listMainVC count] == 0 || _isMain) {
  225. // This is Main
  226. _isMain = YES;
  227. // go Home
  228. [self.navigationController popToRootViewControllerAnimated:NO];
  229. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl typeCloud:app.typeCloud];
  230. _isFolderEncrypted = NO;
  231. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  232. // add list
  233. [app.listMainVC setObject:self forKey:_serverUrl];
  234. // setting Networking
  235. [[CCNetworking sharedNetworking] settingDelegate:self];
  236. [[CCNetworking sharedNetworking] settingAccount];
  237. // populate shared Link & User variable
  238. [CCCoreData populateSharesVariableFromDBActiveAccount:app.activeAccount sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup];
  239. // Load Datasource
  240. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  241. // Load Folder
  242. [self readFolderWithForced:NO];
  243. // Load photo datasorce
  244. if (app.activeAccount && app.activeUrl && app.activePhotosCameraUpload)
  245. [app.activePhotosCameraUpload reloadDatasourceForced];
  246. // remove all of detail
  247. if (app.activeDetail)
  248. [app.activeDetail removeAllView];
  249. // remove all Notification Messages
  250. [app.listOfNotifications removeAllObjects];
  251. // home main
  252. app.homeMain = self;
  253. // Initializations
  254. [app applicationInitialized];
  255. } else {
  256. // reload datasource
  257. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  258. }
  259. }
  260. #pragma --------------------------------------------------------------------------------------------
  261. #pragma mark ===== AlertView =====
  262. #pragma --------------------------------------------------------------------------------------------
  263. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  264. {
  265. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  266. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  267. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  268. if (alertView.tag == alertRename && buttonIndex == 1) {
  269. if ([_metadata.model isEqualToString:@"note"]) {
  270. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  271. } else {
  272. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  273. }
  274. }
  275. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  276. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  277. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  278. [[CCOfflineFileFolder sharedOfflineFileFolder] addOfflineFolder:dir];
  279. [self performSelector:@selector(reloadDatasource) withObject:nil afterDelay:0.1];
  280. }
  281. }
  282. // accept only number char > 0
  283. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  284. {
  285. /* Retrieve a text field at an index -
  286. raises NSRangeException when textFieldIndex is out-of-bounds.
  287. The field at index 0 will be the first text field
  288. (the single field or the login field),
  289. The field at index 1 will be the password field. */
  290. /*
  291. 1> Get the Text Field in alertview
  292. 2> Get the text of that Text Field
  293. 3> Verify that text length
  294. 4> return YES or NO Based on the length
  295. */
  296. if (alertView.tag == alertOfflineFolder) return YES;
  297. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  298. }
  299. #pragma --------------------------------------------------------------------------------------------
  300. #pragma mark ===== Graphic Window =====
  301. #pragma --------------------------------------------------------------------------------------------
  302. - (void)createRefreshControl
  303. {
  304. _refreshControl = [UIRefreshControl new];
  305. _refreshControl.tintColor = COLOR_BRAND;
  306. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  307. [self setRefreshControl:_refreshControl];
  308. }
  309. - (void)deleteRefreshControl
  310. {
  311. [_refreshControl endRefreshing];
  312. self.refreshControl = nil;
  313. }
  314. - (void)refreshControlTarget
  315. {
  316. [self readFolderWithForced:YES];
  317. // Actuate `Peek` feedback (weak boom)
  318. AudioServicesPlaySystemSound(1519);
  319. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  320. }
  321. - (void)setTitleNOAnimation
  322. {
  323. app.isTitleBrandAnimated = NO;
  324. [self setTitle];
  325. }
  326. - (void)setTitleYESAnimation
  327. {
  328. app.isTitleBrandAnimated = YES;
  329. [self setTitle];
  330. }
  331. - (void)setTitle
  332. {
  333. // PopGesture in progress [swipe gesture to switch between views]
  334. if (app.controlCenter.isPopGesture)
  335. return;
  336. // Color text self.navigationItem.title
  337. if ([app.reachability isReachable] == NO)
  338. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : COLOR_NO_CONNECTION}];
  339. else if (_isFolderEncrypted)
  340. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : COLOR_ENCRYPTED}];
  341. else
  342. [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : COLOR_GRAY}];
  343. //if (self.tableView.isEditing) {
  344. if (_isSelectedMode) {
  345. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  346. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  347. self.navigationItem.titleView = nil;
  348. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  349. } else {
  350. // we are in home : LOGO BRAND
  351. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl typeCloud:app.typeCloud]]) {
  352. self.navigationItem.title = nil;
  353. if (app.isTitleBrandAnimated) {
  354. NSArray *animationArray = [NSArray arrayWithObjects:[UIImage imageNamed:image_brandNavigationController1],[UIImage imageNamed:image_brandNavigationController2],[UIImage imageNamed:image_brandNavigationController3],[UIImage imageNamed:image_brandNavigationController2],nil];
  355. _ImageTitleHomeCryptoCloud.animationImages = animationArray;
  356. _ImageTitleHomeCryptoCloud.animationDuration = 0.9;
  357. _ImageTitleHomeCryptoCloud.animationRepeatCount = -1;
  358. [_ImageTitleHomeCryptoCloud startAnimating];
  359. } else {
  360. if ([app.reachability isReachable] == NO) _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationControllerOffline]];
  361. else _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:image_brandNavigationController]];
  362. }
  363. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  364. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuChangeUser)];
  365. [singleTap setNumberOfTapsRequired:1];
  366. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  367. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  368. } else {
  369. self.navigationItem.title = _titleMain;
  370. }
  371. }
  372. }
  373. - (void)setTitleBackgroundTableView
  374. {
  375. if ([_sectionDataSource.allRecordsDataSource count] == 0) {
  376. [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_", nil)];
  377. } else {
  378. [self setTitleBackgroundTableView:nil];
  379. }
  380. }
  381. - (void)setTitleBackgroundTableView:(NSString *)title
  382. {
  383. if (title) {
  384. // message if table is empty
  385. UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
  386. if ([app.reachability isReachable] == NO) {
  387. messageLabel.text = NSLocalizedString(@"_comm_erro_pull_down_", nil);
  388. messageLabel.textColor = COLOR_NO_CONNECTION;
  389. messageLabel.font = RalewayLight(14.0f);
  390. } else {
  391. messageLabel.text = NSLocalizedString(title ,nil);
  392. messageLabel.textColor = [UIColor blackColor];
  393. messageLabel.font = RalewayLight(14.0f);
  394. }
  395. messageLabel.numberOfLines = 0;
  396. messageLabel.textAlignment = NSTextAlignmentCenter;
  397. [messageLabel sizeToFit];
  398. [self.tableView reloadData];
  399. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  400. self.tableView.backgroundView = messageLabel;
  401. } else {
  402. [self.tableView setBackgroundView:nil];
  403. self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
  404. }
  405. }
  406. - (void)setUINavigationBarDefault
  407. {
  408. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  409. UIBarButtonItem *buttonMore, *buttonNotification;
  410. // =
  411. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_more] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  412. buttonMore.enabled = true;
  413. // <
  414. self.navigationController.navigationBar.hidden = NO;
  415. // Notification
  416. if ([app.listOfNotifications count] > 0) {
  417. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_notification] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  418. buttonNotification.tintColor = COLOR_BRAND;
  419. buttonNotification.enabled = true;
  420. }
  421. if (buttonNotification)
  422. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  423. else
  424. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  425. self.navigationItem.leftBarButtonItem = nil;
  426. // close Menu
  427. [app.reSelectMenu close];
  428. }
  429. - (void)setUINavigationBarSelected
  430. {
  431. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  432. UIImage *icon = [UIImage imageNamed:image_more];
  433. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  434. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  435. self.navigationItem.leftBarButtonItem = leftButton;
  436. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  437. }
  438. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  439. {
  440. // close the menus
  441. if (app.reMainMenu.isOpen)
  442. [app.reMainMenu close];
  443. if (app.reSelectMenu.isOpen)
  444. [app.reSelectMenu close];
  445. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  446. }];
  447. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  448. }
  449. - (void)cancelSelect
  450. {
  451. [self tableViewSelect:NO];
  452. }
  453. #pragma --------------------------------------------------------------------------------------------
  454. #pragma mark ===== Document Picker =====
  455. #pragma --------------------------------------------------------------------------------------------
  456. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  457. {
  458. NSLog(@"Cancelled");
  459. }
  460. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  461. {
  462. NSLog(@"Cancelled");
  463. }
  464. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  465. {
  466. documentPicker.delegate = self;
  467. [self presentViewController:documentPicker animated:YES completion:nil];
  468. }
  469. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  470. {
  471. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  472. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  473. __block NSError *error;
  474. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  475. NSString *fileName = [url lastPathComponent];
  476. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  477. NSData *data = [NSData dataWithContentsOfURL:newURL];
  478. if (data && error == nil) {
  479. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  480. // Upload File
  481. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:upload_session taskStatus:taskStatusResume selector:nil selectorPost:nil parentRev:nil errorCode:0 delegate:nil];
  482. } else {
  483. [app messageNotification:@"_error_" description:error.description visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  484. }
  485. } else {
  486. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  487. }
  488. }];
  489. }
  490. }
  491. - (void)openImportDocumentPicker
  492. {
  493. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  494. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  495. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  496. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  497. documentProviderMenu.delegate = self;
  498. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  499. }
  500. #pragma --------------------------------------------------------------------------------------------
  501. #pragma mark ===== Assets Picker =====
  502. #pragma --------------------------------------------------------------------------------------------
  503. - (void)openAssetsPickerController
  504. {
  505. CTAssetSelectionLabel *assetSelectionLabel = [CTAssetSelectionLabel appearance];
  506. assetSelectionLabel.borderWidth = 1.0;
  507. assetSelectionLabel.borderColor = COLOR_BRAND;
  508. [assetSelectionLabel setMargin:2.0];
  509. [assetSelectionLabel setTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12.0], NSForegroundColorAttributeName : [UIColor whiteColor], NSBackgroundColorAttributeName : COLOR_BRAND}];
  510. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  511. dispatch_async(dispatch_get_main_queue(), ^{
  512. // init picker
  513. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  514. // set delegate
  515. picker.delegate = self;
  516. // to show selection order
  517. //picker.showsSelectionIndex = YES;
  518. // to present picker as a form sheet in iPad
  519. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  520. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  521. // present picker
  522. [self presentViewController:picker animated:YES completion:nil];
  523. });
  524. }];
  525. }
  526. /*
  527. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  528. {
  529. __block float imageSize;
  530. PHImageRequestOptions *option = [PHImageRequestOptions new];
  531. option.synchronous = YES;
  532. // self Asset
  533. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  534. imageSize = imageData.length;
  535. }];
  536. // Add selected Asset
  537. for (PHAsset *asset in picker.selectedAssets) {
  538. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  539. imageSize = imageData.length + imageSize;
  540. }];
  541. }
  542. if (imageSize > MaxDimensionUpload || (picker.selectedAssets.count >= (pickerControllerMax - _numTaskUploadInProgress))) {
  543. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  544. return NO;
  545. }
  546. return YES;
  547. }
  548. */
  549. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  550. {
  551. [picker dismissViewControllerAnimated:YES completion:^{
  552. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:upload_session];
  553. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  554. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  555. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  556. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  557. [self presentViewController:navigationController animated:YES completion:nil];
  558. }];
  559. }
  560. #pragma --------------------------------------------------------------------------------------------
  561. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  562. #pragma --------------------------------------------------------------------------------------------
  563. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  564. {
  565. // evitiamo il rimando della eventuale photo e/o video
  566. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  567. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  568. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  569. }
  570. }
  571. #pragma --------------------------------------------------------------------------------------------
  572. #pragma mark ===== UnZipFile =====
  573. #pragma --------------------------------------------------------------------------------------------
  574. - (void)unZipFile:(NSString *)fileID
  575. {
  576. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  577. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  578. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  579. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  580. dispatch_async(dispatch_get_main_queue(), ^{
  581. float progress = (float) entryNumber / (float)total;
  582. [_hudDeterminate progress:progress];
  583. });
  584. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  585. dispatch_async(dispatch_get_main_queue(), ^{
  586. [_hudDeterminate hideHud];
  587. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  588. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  589. });
  590. }];
  591. });
  592. }
  593. #pragma --------------------------------------------------------------------------------------------
  594. #pragma mark ===== Create New (OpenModel) =====
  595. #pragma --------------------------------------------------------------------------------------------
  596. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  597. {
  598. UIViewController *viewController;
  599. NSString *fileName, *uuid, *rev, *fileID, *serverUrl;
  600. BOOL modelReadOnly, isLocal;
  601. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  602. [self.tableView deselectRowAtIndexPath:index animated:NO];
  603. if (isnew) {
  604. fileName = nil;
  605. uuid = [CCUtility getUUID];
  606. rev = nil;
  607. fileID = nil;
  608. modelReadOnly = false;
  609. isLocal = false;
  610. serverUrl = _serverUrl;
  611. } else {
  612. fileName = _metadata.fileName;
  613. uuid = _metadata.uuid;
  614. rev = _metadata.rev;
  615. fileID = _metadata.fileID;
  616. modelReadOnly = false;
  617. isLocal = false;
  618. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  619. }
  620. if ([tipo isEqualToString:@"cartadicredito"])
  621. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  622. if ([tipo isEqualToString:@"bancomat"])
  623. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  624. if ([tipo isEqualToString:@"contocorrente"])
  625. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  626. if ([tipo isEqualToString:@"accountweb"])
  627. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  628. if ([tipo isEqualToString:@"patenteguida"])
  629. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  630. if ([tipo isEqualToString:@"cartaidentita"])
  631. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  632. if ([tipo isEqualToString:@"passaporto"])
  633. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  634. if ([tipo isEqualToString:@"note"]) {
  635. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid rev:rev fileID:fileID modelReadOnly:modelReadOnly isLocal:isLocal serverUrl:serverUrl];
  636. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  637. [self presentViewController:navigationController animated:YES completion:nil];
  638. } else {
  639. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  640. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  641. [self presentViewController:navigationController animated:YES completion:nil];
  642. }
  643. }
  644. // New folder or new photo or video
  645. - (void)returnCreate:(NSInteger)type
  646. {
  647. _numTaskUploadInProgress = [[CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session CONTAINS 'upload') AND ((sessionTaskIdentifier >= 0) OR (sessionTaskIdentifierPlist >= 0))", app.activeAccount] context:nil] count];
  648. switch (type) {
  649. /* PLAIN */
  650. case returnCreateFolderPlain: {
  651. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  652. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  653. alertView.tag = alertCreateFolder;
  654. [alertView show];
  655. }
  656. break;
  657. case returnCreateFotoVideoPlain: {
  658. _isPickerCriptate = false;
  659. [self openAssetsPickerController];
  660. }
  661. break;
  662. case returnCreateFilePlain: {
  663. _isPickerCriptate = false;
  664. [self openImportDocumentPicker];
  665. }
  666. break;
  667. /* ENCRYPTED */
  668. case returnCreateFolderEncrypted: {
  669. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  670. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  671. alertView.tag = alertCreateFolderCrypto;
  672. [alertView show];
  673. }
  674. break;
  675. case returnCreateFotoVideoEncrypted: {
  676. _isPickerCriptate = true;
  677. [self openAssetsPickerController];
  678. }
  679. break;
  680. case returnCreateFileEncrypted: {
  681. _isPickerCriptate = true;
  682. [self openImportDocumentPicker];
  683. }
  684. break;
  685. /* UTILITY */
  686. case returnNote:
  687. [self openModel:@"note" isNew:true];
  688. break;
  689. case returnAccountWeb:
  690. [self openModel:@"accountweb" isNew:true];
  691. break;
  692. /* BANK */
  693. case returnCartaDiCredito:
  694. [self openModel:@"cartadicredito" isNew:true];
  695. break;
  696. case returnBancomat:
  697. [self openModel:@"bancomat" isNew:true];
  698. break;
  699. case returnContoCorrente:
  700. [self openModel:@"contocorrente" isNew:true];
  701. break;
  702. /* DOCUMENT */
  703. case returnPatenteGuida:
  704. [self openModel:@"patenteguida" isNew:true];
  705. break;
  706. case returnCartaIdentita:
  707. [self openModel:@"cartaidentita" isNew:true];
  708. break;
  709. case returnPassaporto:
  710. [self openModel:@"passaporto" isNew:true];
  711. break;
  712. }
  713. }
  714. #pragma --------------------------------------------------------------------------------------------
  715. #pragma mark ===== Save selected File =====
  716. #pragma --------------------------------------------------------------------------------------------
  717. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  718. {
  719. if (error)
  720. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  721. else
  722. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  723. }
  724. - (void)saveSelectedFiles
  725. {
  726. NSLog(@"[LOG] Start download selected files ...");
  727. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  728. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  729. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  730. for (CCMetadata *metadata in metadatas) {
  731. if (metadata.directory == NO && [metadata.type isEqualToString:metadataType_file] && ([metadata.typeFile isEqualToString:metadataTypeFile_image] || [metadata.typeFile isEqualToString:metadataTypeFile_video])) {
  732. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  733. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  734. }
  735. }
  736. [_hud hideHud];
  737. });
  738. [self tableViewSelect:NO];
  739. }
  740. #pragma --------------------------------------------------------------------------------------------
  741. #pragma mark ===== Change Password only Nextcloud ownCloud =====
  742. #pragma --------------------------------------------------------------------------------------------
  743. - (void)changePasswordAccount
  744. {
  745. if ([app.typeCloud isEqualToString:typeCloudNextcloud])
  746. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  747. if ([app.typeCloud isEqualToString:typeCloudOwnCloud])
  748. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginOwnCloud"];
  749. [_loginVC setModifyOnlyPassword:YES];
  750. [_loginVC setTypeCloud:app.typeCloud];
  751. [self presentViewController:_loginVC animated:YES completion:nil];
  752. }
  753. #pragma mark -
  754. #pragma --------------------------------------------------------------------------------------------
  755. #pragma mark ===== Peek & Pop =====
  756. #pragma --------------------------------------------------------------------------------------------
  757. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  758. {
  759. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  760. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  761. if (metadata.thumbnailExists && !metadata.cryptated) {
  762. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  763. if (cell) {
  764. previewingContext.sourceRect = cell.frame;
  765. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  766. vc.delegate = self;
  767. vc.metadata = metadata;
  768. return vc;
  769. }
  770. }
  771. return nil;
  772. }
  773. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  774. {
  775. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  776. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  777. }
  778. #pragma mark -
  779. #pragma --------------------------------------------------------------------------------------------
  780. #pragma mark ==== Notification ====
  781. #pragma --------------------------------------------------------------------------------------------
  782. - (void)getNotificationsOfServerSuccess:(NSArray *)listOfNotifications
  783. {
  784. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  785. NSString *old = @"", *new = @"";
  786. // Order by date
  787. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  788. OCNotifications *notification1 = obj1, *notification2 = obj2;
  789. return [notification2.date compare: notification1.date];
  790. }];
  791. // verify if listOfNotifications is changed
  792. for (OCNotifications *notification in listOfNotifications)
  793. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  794. for (OCNotifications *notification in appDelegate.listOfNotifications)
  795. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  796. if (![new isEqualToString:old]) {
  797. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  798. // reload Notification view
  799. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  800. }
  801. // Update NavigationBar
  802. if (!_isSelectedMode)
  803. [self setUINavigationBarDefault];
  804. }
  805. - (void)getNotificationsOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  806. {
  807. // Update NavigationBar
  808. if (!_isSelectedMode)
  809. [self setUINavigationBarDefault];
  810. }
  811. - (void)viewNotification
  812. {
  813. if ([app.listOfNotifications count] > 0) {
  814. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  815. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  816. [self presentViewController:notificationVC animated:YES completion:nil];
  817. }
  818. }
  819. #pragma --------------------------------------------------------------------------------------------
  820. #pragma mark ==== Request Server ====
  821. #pragma --------------------------------------------------------------------------------------------
  822. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  823. {
  824. app.capabilities = capabilities;
  825. }
  826. - (void)getFeaturesSupportedByServerSuccess:(BOOL)hasCapabilitiesSupport hasForbiddenCharactersSupport:(BOOL)hasForbiddenCharactersSupport hasShareSupport:(BOOL)hasShareSupport hasShareeSupport:(BOOL)hasShareeSupport
  827. {
  828. app.hasServerCapabilitiesSupport = hasCapabilitiesSupport;
  829. app.hasServerForbiddenCharactersSupport = hasForbiddenCharactersSupport;
  830. app.hasServerShareSupport = hasShareSupport;
  831. app.hasServerShareeSupport = hasShareeSupport;
  832. if (hasShareSupport || hasShareeSupport)
  833. [self requestSharedByServer];
  834. }
  835. - (void)getInfoServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  836. {
  837. if (errorCode == 401)
  838. [self changePasswordAccount];
  839. }
  840. - (void)requestServerInformation
  841. {
  842. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  843. [app.sharesID removeAllObjects];
  844. app.hasServerForbiddenCharactersSupport = YES;
  845. app.hasServerShareSupport = YES;
  846. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  847. metadataNet.action = actionGetFeaturesSuppServer;
  848. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  849. metadataNet.action = actionGetCapabilities;
  850. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  851. metadataNet.action = actionGetNotificationsOfServer;
  852. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  853. metadataNet.action = actionReadFile;
  854. metadataNet.selector = selectorReadFileQuota;
  855. metadataNet.serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl typeCloud:app.typeCloud];
  856. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  857. }
  858. }
  859. #pragma --------------------------------------------------------------------------------------------
  860. #pragma mark ==== Download Thumbnail ====
  861. #pragma --------------------------------------------------------------------------------------------
  862. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  863. {
  864. __block CCCellMain *cell;
  865. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  866. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  867. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  868. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  869. if (cell.fileImageView.image == nil) {
  870. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  871. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  872. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  873. });
  874. }
  875. }
  876. }
  877. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  878. {
  879. NSLog(@"[LOG] Thumbnail Error %@ %@ (error %ld)", metadataNet.fileName , message, (long)errorCode);
  880. }
  881. - (void)downloadThumbnail:(CCMetadata *)metadata
  882. {
  883. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  884. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  885. metadataNet.action = actionDownloadThumbnail;
  886. metadataNet.fileID = metadata.fileID;
  887. if ([metadata.typeCloud isEqualToString:typeCloudOwnCloud] || [metadata.typeCloud isEqualToString:typeCloudNextcloud])
  888. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl typeCloud:app.typeCloud];
  889. metadataNet.fileNameLocal = metadata.fileID;
  890. metadataNet.fileNamePrint = metadata.fileNamePrint;
  891. metadataNet.options = @"m";
  892. metadataNet.priority = NSOperationQueuePriorityLow;
  893. metadataNet.selector = selectorDownloadThumbnail;
  894. metadataNet.serverUrl = serverUrl;
  895. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  896. }
  897. #pragma --------------------------------------------------------------------------------------------
  898. #pragma mark ==== Download ====
  899. #pragma --------------------------------------------------------------------------------------------
  900. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  901. {
  902. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  903. // File do not exists on server, remove in local
  904. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  905. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser typeCloud:app.typeCloud activeAccount:app.activeAccount];
  906. }
  907. if ([selector isEqualToString:selectorLoadViewImage]) {
  908. dispatch_async(dispatch_get_main_queue(), ^{
  909. // Updating Detail
  910. if (app.activeDetail)
  911. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  912. // Updating Photos
  913. if (app.activePhotosCameraUpload)
  914. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  915. });
  916. } else {
  917. if (errorCode != kCFURLErrorCancelled)
  918. [app messageNotification:@"_download_file_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  919. }
  920. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  921. }
  922. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  923. {
  924. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  925. if (metadata == nil) return;
  926. // reload
  927. if ([selector isEqualToString:selectorReload]) {
  928. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  929. }
  930. // Offline Directory
  931. if ([selector isEqualToString:selectorDownloadOffline]) {
  932. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  933. }
  934. // add Offline
  935. if ([selector isEqualToString:selectorAddOffline] && ![CCCoreData isOfflineDirectoryServerUrl:serverUrl activeAccount:app.activeAccount]) {
  936. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  937. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  938. }
  939. // encrypted file
  940. if ([selector isEqualToString:selectorEncryptFile]) {
  941. [self encryptedFile:metadata];
  942. }
  943. // decrypted file
  944. if ([selector isEqualToString:selectorDecryptFile]) {
  945. [self decryptedFile:metadata];
  946. }
  947. // open View File
  948. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  949. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  950. if ([metadata.typeFile isEqualToString:metadataTypeFile_compress]) {
  951. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID afterDelay:0.1];
  952. } else if ([metadata.typeFile isEqualToString:metadataTypeFile_unknown]) {
  953. selector = selectorOpenIn;
  954. } else {
  955. _metadataSegue = metadata;
  956. _metadataSegue.sessionSelector = selector;
  957. if ([self shouldPerformSegue:serverUrl])
  958. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  959. }
  960. }
  961. // addLocal
  962. if ([selector isEqualToString:selectorAddLocal]) {
  963. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  964. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  965. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  966. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  967. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  968. }
  969. // Open with...
  970. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  971. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  972. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  973. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  974. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  975. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  976. _docController.delegate = self;
  977. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  978. }
  979. // Save to Photo Album
  980. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  981. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  982. if ([metadata.typeFile isEqualToString:metadataTypeFile_image]) {
  983. // evitiamo il rimando photo
  984. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  985. UIImage *image = [UIImage imageWithContentsOfFile:file];
  986. if (image)
  987. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  988. else
  989. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  990. }
  991. if ([metadata.typeFile isEqualToString:metadataTypeFile_video]) {
  992. // we avoid the cross-reference video
  993. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  994. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  995. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  996. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  997. } else {
  998. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  999. }
  1000. }
  1001. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1002. }
  1003. // Copy File
  1004. if ([selector isEqualToString:selectorLoadCopy]) {
  1005. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1006. [self copyFileToPasteboard:metadata];
  1007. }
  1008. // download and view a template
  1009. if ([selector isEqualToString:selectorLoadModelView]) {
  1010. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud directoryUser:app.directoryUser];
  1011. [self openModel:metadata.model isNew:false];
  1012. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1013. }
  1014. //download file plist
  1015. if ([selector isEqualToString:selectorLoadPlist]) {
  1016. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud directoryUser:app.directoryUser];
  1017. long countSelectorLoadPlist = 0;
  1018. for (NSOperation *operation in [app.netQueue operations]) {
  1019. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  1020. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1021. countSelectorLoadPlist++;
  1022. }
  1023. }
  1024. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1025. dispatch_async(dispatch_get_main_queue(), ^{
  1026. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1027. });
  1028. }
  1029. }
  1030. //selectorLoadViewImage
  1031. if ([selector isEqualToString:selectorLoadViewImage]) {
  1032. dispatch_async(dispatch_get_main_queue(), ^{
  1033. // Detail
  1034. if (app.activeDetail)
  1035. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1036. // Photos
  1037. if (app.activePhotosCameraUpload)
  1038. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1039. });
  1040. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1041. }
  1042. // if exists postselector call self with selectorPost
  1043. if ([selectorPost length] > 0)
  1044. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1045. }
  1046. - (void)downloadSelectedFiles
  1047. {
  1048. NSLog(@"[LOG] Start download selected files ...");
  1049. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1050. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1051. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1052. for (CCMetadata *metadata in selectedMetadatas) {
  1053. if (metadata.directory == NO && [metadata.type isEqualToString:metadataType_file]) {
  1054. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1055. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  1056. }
  1057. }
  1058. [_hud hideHud];
  1059. });
  1060. [self tableViewSelect:NO];
  1061. }
  1062. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1063. {
  1064. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1065. for (TableMetadata *recordMetadata in records) {
  1066. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1067. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1068. metadataNet.action = actionDownloadFile;
  1069. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1070. metadataNet.downloadData = NO;
  1071. metadataNet.downloadPlist = YES;
  1072. metadataNet.selector = selectorLoadPlist;
  1073. metadataNet.serverUrl = serverUrl;
  1074. metadataNet.session = download_session_foreground;
  1075. metadataNet.taskStatus = taskStatusResume;
  1076. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1077. }
  1078. }
  1079. }
  1080. #pragma --------------------------------------------------------------------------------------------
  1081. #pragma mark ===== Upload new Photos/Videos =====
  1082. #pragma --------------------------------------------------------------------------------------------
  1083. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1084. {
  1085. // Automatic upload
  1086. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1087. [app loadTableAutomaticUploadForSelector:selector];
  1088. // Read File test do not exists
  1089. if (errorCode == CCErrorFileUploadNotFound && fileID) {
  1090. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1091. // reUpload
  1092. if (metadata)
  1093. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:taskStatusResume];
  1094. }
  1095. // Print error
  1096. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1097. [app messageNotification:@"_upload_file_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  1098. }
  1099. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1100. }
  1101. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1102. {
  1103. // Automatic upload
  1104. if([selector isEqualToString:selectorUploadAutomatic] || [selector isEqualToString:selectorUploadAutomaticAll])
  1105. [app loadTableAutomaticUploadForSelector:selector];
  1106. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1107. [self readFolderWithForced:YES];
  1108. } else {
  1109. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1110. }
  1111. }
  1112. //
  1113. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1114. //
  1115. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1116. {
  1117. [_hud visibleHudTitle:nil mode:MBProgressHUDModeIndeterminate color:nil];
  1118. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1119. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1120. });
  1121. }
  1122. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1123. {
  1124. NSArray *assets = [arguments objectAtIndex:0];
  1125. NSString *serverUrl = [arguments objectAtIndex:1];
  1126. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1127. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1128. NSString * session = [arguments objectAtIndex:4];
  1129. // remove title (graphics)
  1130. [self setTitleBackgroundTableView:nil];
  1131. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud];
  1132. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1133. // Create if request the folder for Photos
  1134. if ((useSubFolder || [serverUrl isEqualToString:folderPhotos]) && [_serverUrl isEqualToString:serverUrl] == NO){
  1135. if(![app.activePhotosCameraUpload createFolder:folderPhotos]) {
  1136. [_hud hideHud];
  1137. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1138. return;
  1139. }
  1140. }
  1141. // Create if request the subfolders
  1142. if (useSubFolder) {
  1143. for (NSString *dateSubFolder in [CCUtility createNameSubFolder:assets]) {
  1144. if(![app.activePhotosCameraUpload createFolder:[NSString stringWithFormat:@"%@/%@", folderPhotos, dateSubFolder]]) {
  1145. [_hud hideHud];
  1146. [app messageNotification:@"_error_" description:@"_error_createsubfolders_upload_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  1147. return;
  1148. }
  1149. }
  1150. }
  1151. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1152. for (PHAsset *asset in assets) {
  1153. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: keyFileNameMask];
  1154. NSDate *assetDate = asset.creationDate;
  1155. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1156. // Create serverUrl if use sub folder
  1157. if (useSubFolder) {
  1158. [formatter setDateFormat:@"yyyy"];
  1159. NSString *yearString = [formatter stringFromDate:assetDate];
  1160. [formatter setDateFormat:@"MM"];
  1161. NSString *monthString = [formatter stringFromDate:assetDate];
  1162. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1163. }
  1164. // Check if is in upload
  1165. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1166. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1167. if ([isRecordInSessions count] > 0) {
  1168. // next upload
  1169. continue;
  1170. } else {
  1171. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1172. if ([app.typeCloud isEqualToString:typeCloudNextcloud] || [app.typeCloud isEqualToString:typeCloudOwnCloud]) {
  1173. metadataNet.action = actionReadFile;
  1174. metadataNet.identifier = asset.localIdentifier;
  1175. metadataNet.cryptated = cryptated;
  1176. metadataNet.fileName = fileName;
  1177. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1178. metadataNet.session = session;
  1179. metadataNet.selector = selectorReadFileUploadFile;
  1180. metadataNet.serverUrl = serverUrl;
  1181. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1182. }
  1183. }
  1184. }
  1185. [_hud hideHud];
  1186. }
  1187. #pragma --------------------------------------------------------------------------------------------
  1188. #pragma mark ==== Read File ====
  1189. #pragma --------------------------------------------------------------------------------------------
  1190. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1191. {
  1192. // UploadFile
  1193. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1194. // File not exists
  1195. if (errorCode == 404) {
  1196. metadataNet.action = actionUploadAsset;
  1197. metadataNet.errorCode = 0;
  1198. metadataNet.selector = selectorUploadFile;
  1199. metadataNet.selectorPost = nil;
  1200. metadataNet.taskStatus = taskStatusResume;
  1201. if ([metadataNet.session containsString:@"wwan"])
  1202. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1203. else
  1204. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1205. } else {
  1206. // error ho many retry befor notification and go to on next asses
  1207. if (metadataNet.errorRetry < 3) {
  1208. // Retry read file
  1209. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1210. } else {
  1211. // STOP check file, view message error
  1212. [app messageNotification:@"_upload_file_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  1213. }
  1214. }
  1215. }
  1216. }
  1217. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1218. {
  1219. // ReadFile Folder for change rev
  1220. if ([metadataNet.selector isEqualToString:selectorReadFileFolder]) {
  1221. NSString *rev = [CCCoreData getDirectoryRevFromServerUrl:metadataNet.serverUrl activeAccount:app.activeAccount];
  1222. if (![metadata.rev isEqualToString:rev]) {
  1223. NSLog(@"Change etag, force reload folder %@", metadataNet.serverUrl);
  1224. [CCCoreData setDirectoryRev:metadata.rev serverUrl:metadataNet.serverUrl activeAccount:app.activeAccount];
  1225. [CCCoreData clearDateReadDirectory:metadataNet.serverUrl activeAccount:app.activeAccount];
  1226. CCMain *viewController = [app.listMainVC objectForKey:metadataNet.serverUrl];
  1227. if (viewController)
  1228. [viewController clearDateReadDataSource:nil];
  1229. }
  1230. }
  1231. // UploadFile
  1232. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1233. metadataNet.action = actionUploadAsset;
  1234. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1235. metadataNet.selector = selectorUploadFile;
  1236. metadataNet.selectorPost = nil;
  1237. metadataNet.taskStatus = taskStatusResume;
  1238. if ([metadataNet.session containsString:@"wwan"])
  1239. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1240. else
  1241. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1242. }
  1243. // Quota
  1244. if ([metadataNet.selector isEqualToString:selectorReadFileQuota]) {
  1245. if (app.activeSettings)
  1246. [app.activeSettings reloadForm];
  1247. }
  1248. }
  1249. #pragma --------------------------------------------------------------------------------------------
  1250. #pragma mark ==== Read Folder ====
  1251. #pragma --------------------------------------------------------------------------------------------
  1252. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1253. {
  1254. // verify active user
  1255. TableAccount *record = [CCCoreData getActiveAccount];
  1256. [_hud hideHud];
  1257. [_refreshControl endRefreshing];
  1258. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1259. if (message && [record.account isEqualToString:metadataNet.account])
  1260. [app messageNotification:@"_error_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  1261. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1262. if (errorCode == 401)
  1263. [self changePasswordAccount];
  1264. }
  1265. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions rev:(NSString *)rev metadatas:(NSArray *)metadatas
  1266. {
  1267. // verify active user
  1268. TableAccount *record = [CCCoreData getActiveAccount];
  1269. if (![record.account isEqualToString:metadataNet.account])
  1270. return;
  1271. // save father e update permission
  1272. _fatherPermission = permissions;
  1273. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, metadataNet.directoryID]];
  1274. NSArray *recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, metadataNet.directoryID] context:nil];
  1275. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1276. for (CCMetadata *metadata in metadatas) {
  1277. // type of file
  1278. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1279. // if crypto do not insert
  1280. if (typeFilename == metadataTypeFilenameCrypto) continue;
  1281. // verify if the record encrypted has plist + crypto
  1282. if (typeFilename == metadataTypeFilenamePlist && metadata.directory == NO) {
  1283. BOOL isCryptoComplete = NO;
  1284. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1285. for (CCMetadata *completeMetadata in metadatas) {
  1286. if (completeMetadata.cryptated == NO) continue;
  1287. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1288. isCryptoComplete = YES;
  1289. break;
  1290. }
  1291. }
  1292. if (isCryptoComplete == NO) continue;
  1293. }
  1294. // verify if the record is in download/upload progress
  1295. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1296. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1297. // Upload
  1298. if (metadataDB.session && [metadataDB.session rangeOfString:@"upload"].location != NSNotFound) {
  1299. NSString *sessionID = metadataDB.sessionID;
  1300. // rename SessionID -> fileID
  1301. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1302. metadataDB.session = @"";
  1303. metadataDB.date = metadata.date;
  1304. metadataDB.fileID = metadata.fileID;
  1305. metadataDB.rev = metadata.fileID;
  1306. metadataDB.sessionError = @"";
  1307. metadataDB.sessionID = @"";
  1308. metadataDB.sessionTaskIdentifier = taskIdentifierDone;
  1309. metadataDB.sessionTaskIdentifierPlist = taskIdentifierDone;
  1310. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud context:nil];
  1311. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1312. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1313. continue;
  1314. }
  1315. // download in progress
  1316. if (metadataDB.session && [metadataDB.session rangeOfString:@"download"].location != NSNotFound) continue;
  1317. }
  1318. // end test, insert in CoreData
  1319. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud context:nil];
  1320. }
  1321. // read plist
  1322. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1323. // File is changed ??
  1324. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1325. [[CCOfflineFileFolder sharedOfflineFileFolder] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount offline:NO];
  1326. });
  1327. // this is the same directory
  1328. if ([metadataNet.serverUrl isEqualToString:_serverUrl]) {
  1329. // reload
  1330. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1331. // stoprefresh
  1332. [_refreshControl endRefreshing];
  1333. // Enable change user
  1334. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1335. [_hud hideHud];
  1336. }
  1337. }
  1338. - (void)readFolderWithForced:(BOOL)forced
  1339. {
  1340. [self setTitleBackgroundTableView:nil];
  1341. // init control
  1342. if (!_serverUrl || !app.activeAccount)
  1343. return;
  1344. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1345. // Search Mode
  1346. if (_isSearchMode) {
  1347. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName delegate:self];
  1348. [self tableViewReload];
  1349. return;
  1350. }
  1351. if (([CCCoreData isDirectoryOutOfDate:dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) && directoryID && app.activeAccount) {
  1352. if (_refreshControl.isRefreshing == NO)
  1353. [_hud visibleIndeterminateHud];
  1354. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1355. metadataNet.action = actionReadFolder;
  1356. metadataNet.date = [NSDate date];
  1357. metadataNet.directoryID = directoryID;
  1358. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1359. metadataNet.selector = selectorReadFolder;
  1360. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:directoryID activeAccount:app.activeAccount];
  1361. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1362. } else {
  1363. if ([_sectionDataSource.allRecordsDataSource count] == 0) [self setTitleBackgroundTableView:NSLocalizedString(@"_no_file_pull_down_",nil)];
  1364. else [self setTitleBackgroundTableView:nil];
  1365. }
  1366. }
  1367. #pragma mark -
  1368. #pragma --------------------------------------------------------------------------------------------
  1369. #pragma mark ===== Search =====
  1370. #pragma --------------------------------------------------------------------------------------------
  1371. -(void) updateSearchResultsForSearchController:(UISearchController *)searchController
  1372. {
  1373. _isSearchMode = YES;
  1374. _sectionDataSource = [CCSectionDataSource new];
  1375. [self deleteRefreshControl];
  1376. if (searchController.searchBar.text.length > 2) {
  1377. _searchFileName = searchController.searchBar.text;
  1378. [self readFolderWithForced:YES];
  1379. }
  1380. //let scopes = resultSearchController.searchBar.scopeButtonTitles! as [String]
  1381. //let currentScope = scopes[resultSearchController.searchBar.selectedScopeButtonIndex] as String
  1382. }
  1383. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1384. {
  1385. _isSearchMode = NO;
  1386. [self.searchController setActive:NO];
  1387. [self createRefreshControl];
  1388. // forse reload
  1389. _dateReadDataSource = nil;
  1390. [self reloadDatasource];
  1391. }
  1392. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1393. {
  1394. }
  1395. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1396. {
  1397. }
  1398. #pragma mark -
  1399. #pragma --------------------------------------------------------------------------------------------
  1400. #pragma mark ===== Delete File or Folder =====
  1401. #pragma --------------------------------------------------------------------------------------------
  1402. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1403. {
  1404. [self deleteFileOrFolderSuccess:metadataNet];
  1405. }
  1406. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1407. {
  1408. [_queueSelector removeObject:metadataNet.selector];
  1409. if ([_queueSelector count] == 0) {
  1410. [_hud hideHud];
  1411. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1412. // next
  1413. if ([_selectedMetadatas count] > 0) {
  1414. [_selectedMetadatas removeObjectAtIndex:0];
  1415. if ([_selectedMetadatas count] > 0)
  1416. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1417. }
  1418. }
  1419. }
  1420. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1421. {
  1422. if (metadata.cryptated) {
  1423. [_queueSelector addObject:selectorDeleteCrypto];
  1424. [_queueSelector addObject:selectorDeletePlist];
  1425. } else {
  1426. [_queueSelector addObject:selectorDelete];
  1427. }
  1428. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1429. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1430. }
  1431. - (void)deleteSelectionFile
  1432. {
  1433. [_selectedMetadatas removeAllObjects];
  1434. [_queueSelector removeAllObjects];
  1435. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1436. _numSelectedMetadatas = [_selectedMetadatas count];
  1437. if ([_selectedMetadatas count] > 0)
  1438. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1439. [self tableViewSelect:NO];
  1440. }
  1441. - (void)deleteFile
  1442. {
  1443. [_selectedMetadatas removeAllObjects];
  1444. [_queueSelector removeAllObjects];
  1445. _numSelectedMetadatas = 1;
  1446. [_selectedMetadatas addObject:_metadata];
  1447. if ([_selectedMetadatas count] > 0)
  1448. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1449. [self tableViewSelect:NO];
  1450. }
  1451. #pragma --------------------------------------------------------------------------------------------
  1452. #pragma mark ===== Rename / Move =====
  1453. #pragma --------------------------------------------------------------------------------------------
  1454. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1455. {
  1456. [self readFolderWithForced:YES];
  1457. }
  1458. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1459. {
  1460. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1461. }
  1462. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1463. {
  1464. CCTemplates *templates = [[CCTemplates alloc] init];
  1465. CCCrypto *crypto = [[CCCrypto alloc] init];
  1466. NSMutableDictionary *field = [crypto getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1467. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1468. if (fileNameModel) {
  1469. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1470. metadataNet.action = actionUploadTemplate;
  1471. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1472. metadataNet.fileNamePrint = fileName;
  1473. metadataNet.rev = metadata.rev;
  1474. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1475. metadataNet.session = upload_session_foreground;
  1476. metadataNet.taskStatus = taskStatusResume;
  1477. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1478. metadataNet.selectorPost = selectorAddOffline;
  1479. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1480. }
  1481. }
  1482. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1483. {
  1484. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1485. [_hud hideHud];
  1486. if (message)
  1487. [app messageNotification:@"_move_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  1488. [_selectedMetadatas removeAllObjects];
  1489. [_queueSelector removeAllObjects];
  1490. }
  1491. }
  1492. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1493. {
  1494. [_queueSelector removeObject:metadataNet.selector];
  1495. if ([_queueSelector count] == 0) {
  1496. [_hud hideHud];
  1497. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1498. NSString *directoryID = metadataNet.directoryID;
  1499. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1500. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1501. // FILE -> Metadata
  1502. if (metadataNet.directory == NO) {
  1503. // move metadata
  1504. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1505. }
  1506. // DIRECTORY -> Directory - CCMetadata
  1507. if (metadataNet.directory == YES) {
  1508. // delete all dir / subdir
  1509. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addServerUrl:fileName] activeAccount:app.activeAccount];
  1510. // delete all metadata and local file in dir / subdir
  1511. for (NSString *directoryIDDelete in directoryIDs)
  1512. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1513. // move metadata
  1514. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1515. // Add new directory
  1516. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1517. [CCCoreData addDirectory:newDirectory date:[NSDate date] permissions:nil activeAccount:app.activeAccount];
  1518. // Check Offline
  1519. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1520. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1521. }
  1522. // reload Datasource
  1523. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced])
  1524. [self readFolderWithForced:YES];
  1525. else
  1526. [self reloadDatasource];
  1527. // Next file
  1528. [_selectedMetadatas removeObjectAtIndex:0];
  1529. [self moveFileOrFolder:metadataNet.serverUrlTo];
  1530. }
  1531. }
  1532. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1533. {
  1534. if ([_selectedMetadatas count] > 0) {
  1535. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1536. // Plain
  1537. if (metadata.cryptated == NO) {
  1538. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1539. metadataNet.action = actionMoveFileOrFolder;
  1540. metadataNet.directory = metadata.directory;
  1541. metadataNet.fileID = metadata.fileID;
  1542. metadataNet.directoryID = metadata.directoryID;
  1543. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1544. metadataNet.fileName = metadata.fileName;
  1545. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1546. metadataNet.fileNameTo = metadata.fileName;
  1547. metadataNet.rev = metadata.rev;
  1548. metadataNet.selector = selectorMove;
  1549. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1550. metadataNet.serverUrlTo = serverUrlTo;
  1551. [_queueSelector addObject:metadataNet.selector];
  1552. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1553. }
  1554. // cyptated
  1555. if (metadata.cryptated == YES) {
  1556. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1557. metadataNet.action = actionMoveFileOrFolder;
  1558. metadataNet.directory = metadata.directory;
  1559. metadataNet.fileID = metadata.fileID;
  1560. metadataNet.directoryID = metadata.directoryID;
  1561. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1562. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1563. metadataNet.rev = metadata.rev;
  1564. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1565. metadataNet.serverUrlTo = serverUrlTo;
  1566. // data
  1567. metadataNet.fileName = metadata.fileNameData;
  1568. metadataNet.fileNameTo = metadata.fileNameData;
  1569. metadataNet.selector = selectorMoveCrypto;
  1570. [_queueSelector addObject:metadataNet.selector];
  1571. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1572. // plist
  1573. metadataNet.fileName = metadata.fileName;
  1574. metadataNet.fileNameTo = metadata.fileName;
  1575. metadataNet.selector = selectorMovePlist;
  1576. [_queueSelector addObject:metadataNet.selector];
  1577. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1578. }
  1579. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1580. }
  1581. }
  1582. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1583. {
  1584. // Test
  1585. if ([_serverUrl isEqualToString:serverUrlTo]) {
  1586. [self tableViewSelect:NO];
  1587. return;
  1588. }
  1589. [_selectedMetadatas removeAllObjects];
  1590. [_queueSelector removeAllObjects];
  1591. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1592. _numSelectedMetadatas = [_selectedMetadatas count];
  1593. [self moveFileOrFolder:serverUrlTo];
  1594. [self tableViewSelect:NO];
  1595. }
  1596. - (void)moveOpenWindow:(NSArray *)indexPaths
  1597. {
  1598. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1599. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1600. viewController.delegate = self;
  1601. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1602. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1603. viewController.tintColor = COLOR_BRAND;
  1604. viewController.barTintColor = COLOR_BAR;
  1605. viewController.tintColorTitle = COLOR_GRAY;
  1606. viewController.networkingOperationQueue = app.netQueue;
  1607. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1608. [self presentViewController:navigationController animated:YES completion:nil];
  1609. }
  1610. #pragma --------------------------------------------------------------------------------------------
  1611. #pragma mark ===== Create folder =====
  1612. #pragma --------------------------------------------------------------------------------------------
  1613. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1614. {
  1615. [_hud hideHud];
  1616. if (message)
  1617. [app messageNotification:@"_create_folder_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  1618. }
  1619. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1620. {
  1621. [_hud hideHud];
  1622. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1623. [CCCoreData addDirectory:newDirectory date:[NSDate date] permissions:nil activeAccount:app.activeAccount];
  1624. // Check Offline
  1625. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1626. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1627. // Load Folder or the Datasource
  1628. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1629. [self readFolderWithForced:YES];
  1630. } else {
  1631. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1632. }
  1633. }
  1634. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1635. {
  1636. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1637. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1638. if (![fileNameFolder length]) return;
  1639. if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud];
  1640. else metadataNet.serverUrl = _serverUrl;
  1641. metadataNet.action = actionCreateFolder;
  1642. if (folderCameraUpload)
  1643. metadataNet.options = @"folderCameraUpload";
  1644. metadataNet.fileName = fileNameFolder;
  1645. metadataNet.selector = selectorCreateFolder;
  1646. metadataNet.selectorPost = selectorReadFolderForced;
  1647. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1648. if (!folderCameraUpload)
  1649. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1650. }
  1651. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1652. {
  1653. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1654. CCCrypto *crypto = [[CCCrypto alloc] init];
  1655. NSString *fileNamePlist;
  1656. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1657. if (![fileNameFolder length]) return;
  1658. NSString *title = [AESCrypt encrypt:fileNameFolder password:[crypto getKeyPasscode:[CCUtility getUUID]]];
  1659. fileNamePlist = [crypto createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1660. [crypto createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1661. // Create folder
  1662. metadataNet.action = actionCreateFolder;
  1663. metadataNet.fileName = fileNamePlist;
  1664. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1665. metadataNet.selector = selectorCreateFolder;
  1666. metadataNet.serverUrl = _serverUrl;
  1667. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1668. // upload plist file
  1669. metadataNet.action = actionUploadOnlyPlist;
  1670. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1671. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1672. metadataNet.selectorPost = selectorReadFolderForced;
  1673. metadataNet.serverUrl = _serverUrl;
  1674. metadataNet.session = upload_session_foreground;
  1675. metadataNet.taskStatus = taskStatusResume;
  1676. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1677. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1678. }
  1679. - (void)createFolderCameraUpload
  1680. {
  1681. [self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1682. }
  1683. #pragma --------------------------------------------------------------------------------------------
  1684. #pragma mark ===== Encrypted / Decrypted Folder =====
  1685. #pragma --------------------------------------------------------------------------------------------
  1686. - (void)encyptedDecryptedFolder
  1687. {
  1688. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1689. if (_metadata.cryptated) {
  1690. // DECRYPTED
  1691. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1692. //-------------------------- RENAME -------------------------------------------//
  1693. metadataNet.action = actionMoveFileOrFolder;
  1694. metadataNet.fileID = _metadata.fileID;
  1695. metadataNet.fileName = _metadata.fileNameData;
  1696. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1697. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1698. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1699. metadataNet.selector = selectorRename;
  1700. metadataNet.serverUrl = serverUrl;
  1701. metadataNet.serverUrlTo = serverUrl;
  1702. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1703. //-------------------------- DELETE -------------------------------------------//
  1704. metadataNet.action = actionDeleteFileDirectory;
  1705. metadataNet.fileID = _metadata.fileID;
  1706. metadataNet.fileName = _metadata.fileName;
  1707. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1708. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1709. metadataNet.selector = selectorDeletePlist;
  1710. metadataNet.selectorPost = selectorReadFolderForced;
  1711. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1712. } else {
  1713. // ENCRYPTED
  1714. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1715. CCCrypto *crypto = [[CCCrypto alloc] init];
  1716. // Create File Plist
  1717. NSString *fileNameCrypto = [crypto createFileDirectoryPlist:_metadata];
  1718. //-------------------------- RENAME -------------------------------------------//
  1719. metadataNet.action = actionMoveFileOrFolder;
  1720. metadataNet.fileID = _metadata.fileID;
  1721. metadataNet.fileName = _metadata.fileName;
  1722. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1723. metadataNet.fileNameTo = fileNameCrypto;
  1724. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1725. metadataNet.selector = selectorRename;
  1726. metadataNet.serverUrl = serverUrl;
  1727. metadataNet.serverUrlTo = serverUrl;
  1728. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1729. //-------------------------- UPLOAD -------------------------------------------//
  1730. metadataNet.action = actionUploadOnlyPlist;
  1731. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1732. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1733. metadataNet.selectorPost = selectorReadFolderForced;
  1734. metadataNet.serverUrl = serverUrl;
  1735. metadataNet.session = upload_session_foreground;
  1736. metadataNet.taskStatus = taskStatusResume;
  1737. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1738. }
  1739. }
  1740. #pragma --------------------------------------------------------------------------------------------
  1741. #pragma mark ===== Encrypted/Decrypted File =====
  1742. #pragma --------------------------------------------------------------------------------------------
  1743. - (void)encryptedSelectedFiles
  1744. {
  1745. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1746. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1747. for (CCMetadata *metadata in selectedMetadatas) {
  1748. if (metadata.cryptated == NO && metadata.directory == NO)
  1749. [metadatas addObject:metadata];
  1750. }
  1751. if ([metadatas count] > 0) {
  1752. NSLog(@"[LOG] Start encrypted selected files ...");
  1753. for (CCMetadata* metadata in metadatas) {
  1754. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1755. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  1756. }
  1757. }
  1758. [self tableViewSelect:NO];
  1759. }
  1760. - (void)decryptedSelectedFiles
  1761. {
  1762. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1763. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1764. for (CCMetadata *metadata in selectedMetadatas) {
  1765. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1766. [metadatas addObject:metadata];
  1767. }
  1768. if ([metadatas count] > 0) {
  1769. NSLog(@"[LOG] Start decrypted selected files ...");
  1770. for (CCMetadata* metadata in metadatas) {
  1771. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1772. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  1773. }
  1774. }
  1775. [self tableViewSelect:NO];
  1776. }
  1777. - (void)cmdEncryptedDecryptedFile
  1778. {
  1779. NSString *selector;
  1780. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1781. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1782. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1783. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  1784. }
  1785. - (void)encryptedFile:(CCMetadata *)metadata
  1786. {
  1787. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1788. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1789. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1790. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1791. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1792. dispatch_async(dispatch_get_main_queue(), ^{
  1793. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:upload_session taskStatus:taskStatusResume selector:nil selectorPost:nil parentRev:nil errorCode:0 delegate:nil];
  1794. [self performSelector:@selector(reloadDatasource) withObject:nil afterDelay:0.1];
  1795. });
  1796. } else {
  1797. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  1798. }
  1799. }
  1800. - (void)decryptedFile:(CCMetadata *)metadata
  1801. {
  1802. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1803. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1804. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1805. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1806. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1807. dispatch_async(dispatch_get_main_queue(), ^{
  1808. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:upload_session taskStatus:taskStatusResume selector:nil selectorPost:nil parentRev:nil errorCode:0 delegate:nil];
  1809. [self performSelector:@selector(reloadDatasource) withObject:nil afterDelay:0.1];
  1810. });
  1811. } else {
  1812. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  1813. }
  1814. }
  1815. #pragma --------------------------------------------------------------------------------------------
  1816. #pragma mark ===== Progress & Task Button =====
  1817. #pragma --------------------------------------------------------------------------------------------
  1818. - (void)progressTask:(NSString *)fileID serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated progress:(float)progress;
  1819. {
  1820. // Check
  1821. if (!fileID)
  1822. return;
  1823. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1824. if (![serverUrl isEqualToString:_serverUrl])
  1825. return;
  1826. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1827. if (indexPath) {
  1828. CCControlCenterCell *cell = (CCControlCenterCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1829. if (cryptated) cell.progressView.progressTintColor = COLOR_ENCRYPTED;
  1830. else cell.progressView.progressTintColor = COLOR_CLEAR;
  1831. cell.progressView.hidden = NO;
  1832. [cell.progressView setProgress:progress];
  1833. }
  1834. }
  1835. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1836. {
  1837. UITouch * touch = [[event allTouches] anyObject];
  1838. CGPoint location = [touch locationInView:self.tableView];
  1839. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1840. if (indexPath) {
  1841. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1842. if (metadata)
  1843. [self reloadTaskButton:metadata];
  1844. }
  1845. }
  1846. - (void)reloadTaskButton:(CCMetadata *)metadata
  1847. {
  1848. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1849. __block NSURLSessionTask *findTask;
  1850. // DOWNLOAD
  1851. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1852. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1853. for (NSURLSessionUploadTask *task in downloadTasks)
  1854. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1855. findTask = task;
  1856. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1857. [task cancel];
  1858. }
  1859. if (!findTask) {
  1860. dispatch_async(dispatch_get_main_queue(), ^{
  1861. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1862. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1863. [[NSNotificationCenter defaultCenter] postNotificationName:networkingSessionNotification object:object];
  1864. });
  1865. }
  1866. }];
  1867. }
  1868. // UPLOAD
  1869. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1870. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1871. for (NSURLSessionUploadTask *task in uploadTasks)
  1872. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1873. findTask = task;
  1874. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1875. [task cancel];
  1876. }
  1877. if (!findTask) {
  1878. dispatch_async(dispatch_get_main_queue(), ^{
  1879. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1880. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1881. [[NSNotificationCenter defaultCenter] postNotificationName:networkingSessionNotification object:object];
  1882. });
  1883. }
  1884. }];
  1885. }
  1886. }
  1887. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1888. {
  1889. UITouch * touch = [[event allTouches] anyObject];
  1890. CGPoint location = [touch locationInView:self.tableView];
  1891. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1892. if (indexPath) {
  1893. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1894. if (metadata)
  1895. [self cancelTaskButton:metadata reloadTable:YES];
  1896. }
  1897. }
  1898. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  1899. {
  1900. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1901. __block NSURLSessionTask *findTask;
  1902. // DOWNLOAD
  1903. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1904. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1905. for (NSURLSessionTask *task in downloadTasks)
  1906. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1907. findTask = task;
  1908. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1909. [task cancel];
  1910. }
  1911. if (!findTask) {
  1912. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  1913. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1914. [[NSNotificationCenter defaultCenter] postNotificationName:networkingSessionNotification object:object];
  1915. }
  1916. }];
  1917. }
  1918. // UPLOAD
  1919. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1920. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1921. for (NSURLSessionUploadTask *task in uploadTasks)
  1922. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1923. findTask = task;
  1924. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1925. [task cancel];
  1926. }
  1927. if (!findTask) {
  1928. dispatch_async(dispatch_get_main_queue(), ^{
  1929. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  1930. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1931. [[NSNotificationCenter defaultCenter] postNotificationName:networkingSessionNotification object:object];
  1932. });
  1933. }
  1934. }];
  1935. }
  1936. }
  1937. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1938. {
  1939. UITouch * touch = [[event allTouches] anyObject];
  1940. CGPoint location = [touch locationInView:self.tableView];
  1941. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1942. if (indexPath) {
  1943. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1944. if (metadata)
  1945. [self stopTaskButton:metadata];
  1946. }
  1947. }
  1948. - (void)stopTaskButton:(CCMetadata *)metadata
  1949. {
  1950. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1951. __block NSURLSessionTask *findTask;
  1952. // UPLOAD
  1953. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1954. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1955. for (NSURLSessionUploadTask *task in uploadTasks)
  1956. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1957. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1958. findTask = task;
  1959. [task cancel];
  1960. }
  1961. if (!findTask) {
  1962. dispatch_async(dispatch_get_main_queue(), ^{
  1963. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  1964. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1965. [[NSNotificationCenter defaultCenter] postNotificationName:networkingSessionNotification object:object];
  1966. });
  1967. }
  1968. }];
  1969. }
  1970. }
  1971. #pragma --------------------------------------------------------------------------------------------
  1972. #pragma mark ===== Shared =====
  1973. #pragma --------------------------------------------------------------------------------------------
  1974. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1975. {
  1976. [_hud hideHud];
  1977. // change account ?
  1978. TableAccount *record = [CCCoreData getActiveAccount];
  1979. if([record.account isEqualToString:metadataNet.account] == NO)
  1980. return;
  1981. [CCCoreData updateShare:items sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud];
  1982. if (openWindow && ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud])) {
  1983. if (_shareOC) {
  1984. [_shareOC reloadData];
  1985. } else {
  1986. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  1987. // Apriamo la view
  1988. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1989. _shareOC.delegate = self;
  1990. _shareOC.metadata = metadata;
  1991. _shareOC.serverUrl = metadataNet.serverUrl;
  1992. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1993. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1994. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1995. [self presentViewController:_shareOC animated:YES completion:nil];
  1996. }
  1997. }
  1998. [self tableViewReload];
  1999. }
  2000. - (void)requestSharedByServer
  2001. {
  2002. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2003. metadataNet.action = actionReadShareServer;
  2004. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2005. }
  2006. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2007. {
  2008. [_hud hideHud];
  2009. [app messageNotification:@"_share_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  2010. if (_shareOC)
  2011. [_shareOC reloadData];
  2012. [self tableViewReload];
  2013. if (errorCode == 401)
  2014. [self changePasswordAccount];
  2015. }
  2016. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2017. {
  2018. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2019. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  2020. metadataNet.action = actionShare;
  2021. metadataNet.fileID = metadata.fileID;
  2022. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl typeCloud:app.typeCloud];
  2023. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2024. metadataNet.password = password;
  2025. metadataNet.selector = selectorShare;
  2026. metadataNet.serverUrl = serverUrl;
  2027. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2028. }
  2029. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2030. }
  2031. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2032. {
  2033. [_hud hideHud];
  2034. // rimuoviamo la condivisione da db
  2035. [CCCoreData unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount];
  2036. if ([app.typeCloud isEqualToString:typeCloudNextcloud] && _shareOC)
  2037. [_shareOC reloadData];
  2038. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] && _shareOC)
  2039. [_shareOC reloadData];
  2040. [self tableViewReload];
  2041. }
  2042. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2043. {
  2044. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2045. metadataNet.action = actionUnShare;
  2046. metadataNet.fileID = metadata.fileID;
  2047. metadataNet.fileName = metadata.fileName;
  2048. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2049. metadataNet.selector = selectorUnshare;
  2050. metadataNet.serverUrl = serverUrl;
  2051. metadataNet.share = share;
  2052. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2053. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2054. }
  2055. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2056. {
  2057. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2058. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  2059. metadataNet.action = actionUpdateShare;
  2060. metadataNet.fileID = metadata.fileID;
  2061. metadataNet.expirationTime = expirationTime;
  2062. metadataNet.password = password;
  2063. metadataNet.selector = selectorUpdateShare;
  2064. metadataNet.serverUrl = serverUrl;
  2065. metadataNet.share = share;
  2066. metadataNet.sharePermission = permission;
  2067. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2068. }
  2069. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2070. }
  2071. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2072. {
  2073. [_hud hideHud];
  2074. if (_shareOC)
  2075. [_shareOC reloadUserAndGroup:items];
  2076. }
  2077. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2078. {
  2079. [_hud hideHud];
  2080. [app messageNotification:@"_error_" description:message visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  2081. }
  2082. - (void)getUserAndGroup:(NSString *)find
  2083. {
  2084. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2085. if ([app.typeCloud isEqualToString:typeCloudOwnCloud] || [app.typeCloud isEqualToString:typeCloudNextcloud]) {
  2086. metadataNet.action = actionGetUserAndGroup;
  2087. metadataNet.options = find;
  2088. metadataNet.selector = selectorGetUserAndGroup;
  2089. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2090. }
  2091. [_hud visibleIndeterminateHud];
  2092. }
  2093. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2094. {
  2095. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2096. metadataNet.action = actionShareWith;
  2097. metadataNet.fileID = metadata.fileID;
  2098. metadataNet.directoryID = directoryID;
  2099. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl typeCloud:app.typeCloud];
  2100. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2101. metadataNet.serverUrl = serverUrl;
  2102. metadataNet.selector = selectorShare;
  2103. metadataNet.share = user;
  2104. metadataNet.shareeType = shareeType;
  2105. metadataNet.sharePermission = permission;
  2106. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2107. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2108. }
  2109. - (void)openWindowShare:(CCMetadata *)metadata
  2110. {
  2111. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2112. metadataNet.action = actionReadShareServer;
  2113. metadataNet.fileID = metadata.fileID;
  2114. metadataNet.fileName = metadata.fileName;
  2115. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2116. metadataNet.selector = selectorOpenWindowShare;
  2117. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2118. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2119. [_hud visibleIndeterminateHud];
  2120. }
  2121. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2122. {
  2123. CGPoint location = [tapGesture locationInView:self.tableView];
  2124. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2125. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2126. if (metadata)
  2127. [self openWindowShare:metadata];
  2128. }
  2129. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2130. {
  2131. CGPoint location = [tapGesture locationInView:self.tableView];
  2132. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2133. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2134. if (metadata) {
  2135. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2136. vc.metadata = metadata;
  2137. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2138. [self presentViewController:vc animated:YES completion:nil];
  2139. }
  2140. }
  2141. #pragma --------------------------------------------------------------------------------------------
  2142. #pragma mark ===== Offline =====
  2143. #pragma --------------------------------------------------------------------------------------------
  2144. - (void)addOffline:(CCMetadata *)metadata
  2145. {
  2146. if (metadata.errorPasscode || !metadata.uuid) return;
  2147. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2148. if ([metadata.type isEqualToString:metadataType_file])
  2149. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  2150. if ([metadata.type isEqualToString:metadataType_model])
  2151. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  2152. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2153. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2154. }
  2155. - (void)removeOffline:(CCMetadata *)metadata
  2156. {
  2157. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2158. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2159. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2160. }
  2161. #pragma --------------------------------------------------------------------------------------------
  2162. #pragma mark ===== Local =====
  2163. #pragma --------------------------------------------------------------------------------------------
  2164. - (void)addLocal:(CCMetadata *)metadata
  2165. {
  2166. if (metadata.errorPasscode || !metadata.uuid) return;
  2167. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2168. if ([metadata.type isEqualToString:metadataType_file])
  2169. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  2170. if ([metadata.type isEqualToString:metadataType_model]) {
  2171. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2172. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  2173. }
  2174. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2175. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2176. }
  2177. #pragma --------------------------------------------------------------------------------------------
  2178. #pragma mark ===== Reload =====
  2179. #pragma --------------------------------------------------------------------------------------------
  2180. - (void)reloadFile:(CCMetadata *)metadata
  2181. {
  2182. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2183. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorReload selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  2184. }
  2185. #pragma --------------------------------------------------------------------------------------------
  2186. #pragma mark ===== Open in... =====
  2187. #pragma --------------------------------------------------------------------------------------------
  2188. - (void)openIn:(CCMetadata *)metadata
  2189. {
  2190. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2191. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  2192. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2193. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2194. }
  2195. #pragma --------------------------------------------------------------------------------------------
  2196. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2197. #pragma --------------------------------------------------------------------------------------------
  2198. - (void)orderTable:(NSString *)order
  2199. {
  2200. // Clear data-read of DataSource
  2201. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2202. [CCUtility setOrderSettings:order];
  2203. // refresh
  2204. [self reloadDatasource];
  2205. // new menu
  2206. [self createReMainMenu];
  2207. }
  2208. - (void)ascendingTable:(BOOL)ascending
  2209. {
  2210. // Clear data-read of DataSource
  2211. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2212. [CCUtility setAscendingSettings:ascending];
  2213. // refresh
  2214. [self reloadDatasource];
  2215. // new menu
  2216. [self createReMainMenu];
  2217. }
  2218. - (void)directoryOnTop:(BOOL)directoryOnTop
  2219. {
  2220. // Clear data-read of DataSource
  2221. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2222. [CCUtility setDirectoryOnTop:directoryOnTop];
  2223. // refresh
  2224. [self reloadDatasource];
  2225. // new menu
  2226. [self createReMainMenu];
  2227. }
  2228. - (void)tableGroupBy:(NSString *)groupBy
  2229. {
  2230. // Clear data-read of DataSource
  2231. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2232. [CCUtility setGroupBySettings:groupBy];
  2233. // refresh
  2234. [self reloadDatasource];
  2235. // new menu
  2236. [self createReMainMenu];
  2237. }
  2238. #pragma --------------------------------------------------------------------------------------------
  2239. #pragma mark ==== Menu change User ====
  2240. #pragma --------------------------------------------------------------------------------------------
  2241. - (void)menuChangeUser
  2242. {
  2243. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2244. return;
  2245. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [CCCoreData countTableAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2246. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  2247. return;
  2248. }
  2249. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2250. NSMutableArray *menuArray = [[NSMutableArray alloc] init];
  2251. for (TableAccount *record in listTableAccount) {
  2252. if ([record.account isEqualToString:app.activeAccount]) continue;
  2253. CCMenuItem *item = [[CCMenuItem alloc] init];
  2254. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2255. item.argument = record.account;
  2256. if ([record.typeCloud isEqualToString:typeCloudNextcloud]) item.image = [UIImage imageNamed:image_typeCloudNextcloud];
  2257. if ([record.typeCloud isEqualToString:typeCloudOwnCloud]) item.image = [UIImage imageNamed:image_typeCloudOwnCloud];
  2258. item.target = self;
  2259. item.action = @selector(changeDefaultAccount:);
  2260. [menuArray addObject:item];
  2261. }
  2262. if ([menuArray count] == 0)
  2263. return;
  2264. OptionalConfiguration options;
  2265. Color textColor, backgroundColor;
  2266. textColor.R = 0;
  2267. textColor.G = 0;
  2268. textColor.B = 0;
  2269. backgroundColor.R = 1;
  2270. backgroundColor.G = 1;
  2271. backgroundColor.B = 1;
  2272. options.arrowSize = 9;
  2273. options.marginXSpacing = 7;
  2274. options.marginYSpacing = 10;
  2275. options.intervalSpacing = 20;
  2276. options.menuCornerRadius = 6.5;
  2277. options.maskToBackground = NO;
  2278. options.shadowOfMenu = YES;
  2279. options.hasSeperatorLine = YES;
  2280. options.seperatorLineHasInsets = YES;
  2281. options.textColor = textColor;
  2282. options.menuBackgroundColor = backgroundColor;
  2283. [CCMenu setTitleFont:[UIFont systemFontOfSize:12.0]];
  2284. [CCMenu showMenuInView:self.navigationController.view fromRect:self.view.frame menuItems:menuArray withOptions:options];
  2285. }
  2286. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2287. {
  2288. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2289. // STOP, erase all in queue networking
  2290. [app cancelAllOperations];
  2291. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2292. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2293. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2294. if (tableAccount)
  2295. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password activeUID:tableAccount.uid activeAccessToken:tableAccount.token typeCloud:tableAccount.typeCloud];
  2296. // go to home sweet home
  2297. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2298. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2299. });
  2300. }
  2301. #pragma --------------------------------------------------------------------------------------------
  2302. #pragma mark ==== ReMenu ====
  2303. #pragma --------------------------------------------------------------------------------------------
  2304. - (void)createReMenuBackgroundView:(REMenu *)menu
  2305. {
  2306. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2307. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2308. [UIView animateWithDuration:0.2 animations:^{
  2309. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2310. if (height < self.tabBarController.tabBar.frame.size.height)
  2311. height = self.tabBarController.tabBar.frame.size.height;
  2312. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2313. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2314. }];
  2315. }
  2316. - (void)createReMainMenu
  2317. {
  2318. NSString *ordinamento;
  2319. NSString *groupBy = _directoryGroupBy;
  2320. __block NSString *nuovoOrdinamento;
  2321. NSString *titoloNuovo, *titoloAttuale;
  2322. BOOL ascendente;
  2323. __block BOOL nuovoAscendente;
  2324. UIImage *image;
  2325. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2326. if (app.selezionaItem == nil) app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)
  2327. subtitle:@""
  2328. image:[UIImage imageNamed:image_seleziona]
  2329. highlightedImage:nil
  2330. action:^(REMenuItem *item) {
  2331. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2332. [self tableViewSelect:YES];
  2333. }
  2334. }];
  2335. else app.selezionaItem = [app.selezionaItem initWithTitle:NSLocalizedString(@"_select_", nil)
  2336. subtitle:@""
  2337. image:[UIImage imageNamed:image_seleziona]
  2338. highlightedImage:nil
  2339. action:^(REMenuItem *item) {
  2340. if ([_sectionDataSource.allRecordsDataSource count] > 0)
  2341. [self tableViewSelect:YES];
  2342. }];
  2343. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2344. ordinamento = _directoryOrder;
  2345. if ([ordinamento isEqualToString:@"fileName"]) {
  2346. image = [UIImage imageNamed:image_MenuOrdeyByDate];
  2347. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2348. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2349. nuovoOrdinamento = @"fileDate";
  2350. }
  2351. if ([ordinamento isEqualToString:@"fileDate"]) {
  2352. image = [UIImage imageNamed:image_MenuOrderByFileName];
  2353. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2354. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2355. nuovoOrdinamento = @"fileName";
  2356. }
  2357. if (app.ordinaItem == nil) app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2358. subtitle:titoloAttuale
  2359. image:image
  2360. highlightedImage:nil
  2361. action:^(REMenuItem *item) {
  2362. [self orderTable:nuovoOrdinamento];
  2363. }];
  2364. else app.ordinaItem = [app.ordinaItem initWithTitle:titoloNuovo
  2365. subtitle:titoloAttuale
  2366. image:image
  2367. highlightedImage:nil
  2368. action:^(REMenuItem *item) {
  2369. [self orderTable:nuovoOrdinamento];
  2370. }];
  2371. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2372. ascendente = [CCUtility getAscendingSettings];
  2373. if (ascendente) {
  2374. image = [UIImage imageNamed:image_MenuOrdinamentoDiscendente];
  2375. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2376. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2377. nuovoAscendente = false;
  2378. }
  2379. if (!ascendente) {
  2380. image = [UIImage imageNamed:image_MenuOrdinamentoAscendente];
  2381. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2382. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2383. nuovoAscendente = true;
  2384. }
  2385. if (app.ascendenteItem == nil) app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2386. subtitle:titoloAttuale
  2387. image:image
  2388. highlightedImage:nil
  2389. action:^(REMenuItem *item) {
  2390. [self ascendingTable:nuovoAscendente];
  2391. }];
  2392. else app.ascendenteItem = [app.ascendenteItem initWithTitle:titoloNuovo
  2393. subtitle:titoloAttuale
  2394. image:image
  2395. highlightedImage:nil
  2396. action:^(REMenuItem *item) {
  2397. [self ascendingTable:nuovoAscendente];
  2398. }];
  2399. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2400. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2401. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2402. if (app.alphabeticItem == nil) app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2403. subtitle:@""
  2404. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2405. highlightedImage:nil
  2406. action:^(REMenuItem *item) {
  2407. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2408. else [self tableGroupBy:@"alphabetic"];
  2409. }];
  2410. else app.alphabeticItem = [app.alphabeticItem initWithTitle:titoloNuovo
  2411. subtitle:@""
  2412. image:[UIImage imageNamed:image_MenuGroupByAlphabetic]
  2413. highlightedImage:nil
  2414. action:^(REMenuItem *item) {
  2415. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2416. else [self tableGroupBy:@"alphabetic"];
  2417. }];
  2418. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2419. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2420. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2421. if (app.typefileItem == nil) app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2422. subtitle:@""
  2423. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2424. highlightedImage:nil
  2425. action:^(REMenuItem *item) {
  2426. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2427. else [self tableGroupBy:@"typefile"];
  2428. }];
  2429. else app.typefileItem = [app.typefileItem initWithTitle:titoloNuovo
  2430. subtitle:@""
  2431. image:[UIImage imageNamed:image_MenuGroupByTypeFile]
  2432. highlightedImage:nil
  2433. action:^(REMenuItem *item) {
  2434. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2435. else [self tableGroupBy:@"typefile"];
  2436. }];
  2437. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2438. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2439. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2440. if (app.dateItem == nil) app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2441. subtitle:@""
  2442. image:[UIImage imageNamed:image_MenuGroupByDate]
  2443. highlightedImage:nil
  2444. action:^(REMenuItem *item) {
  2445. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2446. else [self tableGroupBy:@"date"];
  2447. }];
  2448. else app.dateItem = [app.dateItem initWithTitle:titoloNuovo
  2449. subtitle:@""
  2450. image:[UIImage imageNamed:image_MenuGroupByDate]
  2451. highlightedImage:nil
  2452. action:^(REMenuItem *item) {
  2453. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2454. else [self tableGroupBy:@"date"];
  2455. }];
  2456. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2457. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2458. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2459. if (app.directoryOnTopItem == nil) app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo
  2460. subtitle:@""
  2461. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2462. highlightedImage:nil
  2463. action:^(REMenuItem *item) {
  2464. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2465. else [self directoryOnTop:YES];
  2466. }];
  2467. else app.directoryOnTopItem = [app.directoryOnTopItem initWithTitle:titoloNuovo
  2468. subtitle:@""
  2469. image:[UIImage imageNamed:image_MenuDirectoryOnTop]
  2470. highlightedImage:nil
  2471. action:^(REMenuItem *item) {
  2472. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2473. else [self directoryOnTop:YES];
  2474. }];
  2475. // REMENU --------------------------------------------------------------------------------------------------------------
  2476. if (app.reMainMenu == nil) app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2477. else app.reMainMenu = [app.reMainMenu initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2478. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2479. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2480. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2481. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2482. app.reMainMenu.separatorHeight = 0.5;
  2483. app.reMainMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2484. app.reMainMenu.backgroundColor = COLOR_BAR;
  2485. app.reMainMenu.textColor = [UIColor blackColor];
  2486. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2487. app.reMainMenu.textShadowColor = nil;
  2488. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2489. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2490. app.reMainMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2491. app.reMainMenu.highlightedSeparatorColor = nil;
  2492. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2493. app.reMainMenu.highlightedTextShadowColor = nil;
  2494. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2495. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2496. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2497. app.reMainMenu.subtitleTextShadowColor = nil;
  2498. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2499. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2500. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2501. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2502. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2503. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2504. app.reMainMenu.borderWidth = 0.3;
  2505. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2506. app.reMainMenu.animationDuration = 0.2;
  2507. app.reMainMenu.closeAnimationDuration = 0.2;
  2508. app.reMainMenu.bounce = NO;
  2509. [app.reMainMenu setClosePreparationBlock:^{
  2510. // Backgroun reMenu (Gesture)
  2511. [_reMenuBackgroundView removeFromSuperview];
  2512. [app.controlCenter disableSingleFingerTap];
  2513. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2514. }];
  2515. }
  2516. - (void)toggleReMainMenu
  2517. {
  2518. if (app.reMainMenu.isOpen) {
  2519. [app.reMainMenu close];
  2520. } else {
  2521. [app.reMainMenu showFromNavigationController:self.navigationController];
  2522. // Backgroun reMenu & (Gesture)
  2523. [self createReMenuBackgroundView:app.reMainMenu];
  2524. [app.controlCenter enableSingleFingerTap:@selector(toggleReMainMenu) target:self];
  2525. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2526. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2527. }
  2528. }
  2529. - (void)createReSelectMenu
  2530. {
  2531. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2532. if (app.deleteItem == nil) app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2533. subtitle:@""
  2534. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2535. highlightedImage:nil
  2536. action:^(REMenuItem *item) {
  2537. [self deleteSelectionFile];
  2538. }];
  2539. else app.deleteItem = [app.deleteItem initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil)
  2540. subtitle:@""
  2541. image:[UIImage imageNamed:image_deleteSelectedFiles]
  2542. highlightedImage:nil
  2543. action:^(REMenuItem *item) {
  2544. [self deleteSelectionFile];
  2545. }];
  2546. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2547. if (app.moveItem == nil) app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2548. subtitle:@""
  2549. image:[UIImage imageNamed:image_moveSelectedFiles]
  2550. highlightedImage:nil
  2551. action:^(REMenuItem *item) {
  2552. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2553. }];
  2554. else app.moveItem = [app.moveItem initWithTitle:NSLocalizedString(@"_move_selected_files_", nil)
  2555. subtitle:@""
  2556. image:[UIImage imageNamed:image_moveSelectedFiles]
  2557. highlightedImage:nil
  2558. action:^(REMenuItem *item) {
  2559. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2560. }];
  2561. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2562. if (app.encryptItem == nil) app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2563. subtitle:@""
  2564. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2565. highlightedImage:nil
  2566. action:^(REMenuItem *item) {
  2567. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil afterDelay:0.1];
  2568. }];
  2569. else app.encryptItem = [app.encryptItem initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil)
  2570. subtitle:@""
  2571. image:[UIImage imageNamed:image_encryptedSelectedFiles]
  2572. highlightedImage:nil
  2573. action:^(REMenuItem *item) {
  2574. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil afterDelay:0.1];
  2575. }];
  2576. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2577. if (app.decryptItem == nil) app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2578. subtitle:@""
  2579. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2580. highlightedImage:nil
  2581. action:^(REMenuItem *item) {
  2582. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil afterDelay:0.1];
  2583. }];
  2584. else app.decryptItem = [app.decryptItem initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil)
  2585. subtitle:@""
  2586. image:[UIImage imageNamed:image_decryptedSelectedFiles]
  2587. highlightedImage:nil
  2588. action:^(REMenuItem *item) {
  2589. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil afterDelay:0.1];
  2590. }];
  2591. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2592. if (app.downloadItem == nil) app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2593. subtitle:@""
  2594. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2595. highlightedImage:nil
  2596. action:^(REMenuItem *item) {
  2597. [self downloadSelectedFiles];
  2598. }];
  2599. else app.downloadItem = [app.downloadItem initWithTitle:NSLocalizedString(@"_download_selected_files_", nil)
  2600. subtitle:@""
  2601. image:[UIImage imageNamed:image_downloadSelectedFiles]
  2602. highlightedImage:nil
  2603. action:^(REMenuItem *item) {
  2604. [self downloadSelectedFiles];
  2605. }];
  2606. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2607. if (app.saveItem == nil) app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2608. subtitle:@""
  2609. image:[UIImage imageNamed:image_saveSelectedFiles]
  2610. highlightedImage:nil
  2611. action:^(REMenuItem *item) {
  2612. [self saveSelectedFiles];
  2613. }];
  2614. else app.saveItem = [app.saveItem initWithTitle:NSLocalizedString(@"_save_selected_files_", nil)
  2615. subtitle:@""
  2616. image:[UIImage imageNamed:image_saveSelectedFiles]
  2617. highlightedImage:nil
  2618. action:^(REMenuItem *item) {
  2619. [self saveSelectedFiles];
  2620. }];
  2621. // REMENU --------------------------------------------------------------------------------------------------------------
  2622. if (app.reSelectMenu == nil)
  2623. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2624. else
  2625. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2626. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2627. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2628. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2629. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2630. app.reSelectMenu.separatorHeight = 0.5;
  2631. app.reSelectMenu.separatorColor = COLOR_SEPARATOR_TABLE;
  2632. app.reSelectMenu.backgroundColor = COLOR_BAR;
  2633. app.reSelectMenu.textColor = [UIColor blackColor];
  2634. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2635. app.reSelectMenu.textShadowColor = nil;
  2636. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2637. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2638. app.reSelectMenu.highlightedBackgroundColor = COLOR_SELECT_BACKGROUND;
  2639. app.reSelectMenu.highlightedSeparatorColor = nil;
  2640. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2641. app.reSelectMenu.highlightedTextShadowColor = nil;
  2642. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2643. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2644. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2645. app.reSelectMenu.subtitleTextShadowColor = nil;
  2646. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2647. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2648. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2649. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2650. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2651. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2652. app.reSelectMenu.borderWidth = 0.3;
  2653. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2654. app.reSelectMenu.closeAnimationDuration = 0.2;
  2655. app.reSelectMenu.animationDuration = 0.2;
  2656. app.reSelectMenu.bounce = NO;
  2657. [app.reSelectMenu setClosePreparationBlock:^{
  2658. // Backgroun reMenu (Gesture)
  2659. [_reMenuBackgroundView removeFromSuperview];
  2660. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2661. }];
  2662. }
  2663. - (void)toggleReSelectMenu
  2664. {
  2665. if (app.reSelectMenu.isOpen) {
  2666. [app.reSelectMenu close];
  2667. } else {
  2668. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2669. // Backgroun reMenu & (Gesture)
  2670. [self createReMenuBackgroundView:app.reSelectMenu];
  2671. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2672. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2673. }
  2674. }
  2675. #pragma --------------------------------------------------------------------------------------------
  2676. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2677. #pragma --------------------------------------------------------------------------------------------
  2678. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2679. {
  2680. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2681. UITableView *tableView = (UITableView*)self.view;
  2682. CGPoint touchPoint = [recognizer locationInView:self.view];
  2683. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2684. if (indexPath)
  2685. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2686. else
  2687. _metadata = nil;
  2688. [self becomeFirstResponder];
  2689. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2690. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2691. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2692. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2693. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2694. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2695. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2696. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2697. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2698. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2699. [menuController setMenuVisible:YES animated:YES];
  2700. }
  2701. }
  2702. - (BOOL)canBecomeFirstResponder
  2703. {
  2704. return YES;
  2705. }
  2706. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2707. {
  2708. // For copy file, copy files, Open in ... :
  2709. //
  2710. // NO Directory
  2711. // NO Error Passcode
  2712. // NO In Session mode (download/upload)
  2713. // NO Template
  2714. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2715. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString:metadataTypeFile_template]) {
  2716. // NO Cryptated with Title lenght = 0
  2717. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2718. return YES;
  2719. }
  2720. return NO;
  2721. }
  2722. if (@selector(copyFiles:) == action) {
  2723. if (_isSelectedMode) {
  2724. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2725. for (CCMetadata *metadata in selectedMetadatas) {
  2726. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString:metadataTypeFile_template]) {
  2727. // NO Cryptated with Title lenght = 0
  2728. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2729. return YES;
  2730. }
  2731. }
  2732. }
  2733. return NO;
  2734. }
  2735. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2736. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2737. NSArray *items = [pasteboard items];
  2738. if ([items count] == 1) {
  2739. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2740. NSDictionary *dic = [items objectAtIndex:0];
  2741. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2742. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2743. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2744. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2745. if (directoryUser) {
  2746. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2747. return YES;
  2748. }
  2749. return NO;
  2750. } else return NO;
  2751. }
  2752. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2753. BOOL isValid = NO;
  2754. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2755. NSArray *items = [pasteboard items];
  2756. if ([items count] <= 1) return NO;
  2757. for (NSDictionary *dic in items) {
  2758. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2759. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2760. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2761. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2762. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2763. if (directoryUser) {
  2764. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2765. isValid = YES;
  2766. }
  2767. }
  2768. return isValid;
  2769. }
  2770. return NO;
  2771. }
  2772. /************************************ COPY ************************************/
  2773. - (void)copyFile:(id)sender
  2774. {
  2775. // Remove all item
  2776. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2777. pasteboard.items = [[NSArray alloc] init];
  2778. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2779. [self copyFileToPasteboard:_metadata];
  2780. } else {
  2781. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2782. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  2783. }
  2784. }
  2785. - (void)copyFiles:(id)sender
  2786. {
  2787. // Remove all item
  2788. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2789. pasteboard.items = [[NSArray alloc] init];
  2790. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2791. for (CCMetadata *metadata in selectedMetadatas) {
  2792. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2793. [self copyFileToPasteboard:metadata];
  2794. } else {
  2795. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2796. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  2797. }
  2798. }
  2799. [self tableViewSelect:NO];
  2800. }
  2801. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2802. {
  2803. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2804. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2805. // key : it.twsweb.Crypto-Cloud.CCMetadata Value : (NSData) metadata
  2806. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], @"it.twsweb.Crypto-Cloud.CCMetadata",nil];
  2807. [items addObject:item];
  2808. [pasteboard setItems:items];
  2809. }
  2810. /************************************ OPEN IN ... ************************************/
  2811. - (void)openinFile:(id)sender
  2812. {
  2813. [self openIn:_metadata];
  2814. }
  2815. /************************************ PASTE ************************************/
  2816. - (void)pasteFile:(id)sender
  2817. {
  2818. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2819. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2820. }
  2821. - (void)pasteFileEncrypted:(id)sender
  2822. {
  2823. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2824. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2825. }
  2826. - (void)pasteFiles:(id)sender
  2827. {
  2828. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2829. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2830. }
  2831. - (void)pasteFilesEncrypted:(id)sender
  2832. {
  2833. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2834. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2835. }
  2836. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2837. {
  2838. for (NSDictionary *dic in items) {
  2839. // key : it.twsweb.Crypto-Cloud.CCMetadata
  2840. // Value : (NSData) metadata
  2841. NSData *dataMetadata = [dic objectForKey:@"it.twsweb.Crypto-Cloud.CCMetadata"];
  2842. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2843. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2844. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2845. if (directoryUser) {
  2846. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2847. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2848. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:upload_session taskStatus:taskStatusResume selector:nil selectorPost:nil parentRev:nil errorCode:0 delegate:nil];
  2849. }
  2850. }
  2851. }
  2852. }
  2853. #pragma --------------------------------------------------------------------------------------------
  2854. #pragma mark ===== Lock Passcode =====
  2855. #pragma --------------------------------------------------------------------------------------------
  2856. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2857. {
  2858. return _failedAttempts;
  2859. }
  2860. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2861. {
  2862. return _lockUntilDate;
  2863. }
  2864. - (void)passcodeViewCloseButtonPressed:(id)sender
  2865. {
  2866. [self dismissViewControllerAnimated:YES completion:nil];
  2867. }
  2868. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2869. {
  2870. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2871. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2872. _lockUntilDate = nil;
  2873. _failedAttempts = 0;
  2874. aResultHandler(YES);
  2875. } else aResultHandler(NO);
  2876. } else aResultHandler(YES);
  2877. }
  2878. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2879. {
  2880. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2881. switch (aViewController.type) {
  2882. case BKPasscodeViewControllerCheckPasscodeType: {
  2883. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2884. CCCrypto *crypto = [[CCCrypto alloc] init];
  2885. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2886. if ([crypto verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2887. // scriviamo il passcode
  2888. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2889. [self readFolderWithForced:YES];
  2890. } else {
  2891. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2892. [alertView show];
  2893. }
  2894. }
  2895. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2896. // possiamo procedere alla prossima directory
  2897. [self performSegueDirectoryWithControlPasscode:false];
  2898. // avviamo la sessione Passcode Lock con now
  2899. app.sessionePasscodeLock = [NSDate date];
  2900. }
  2901. // disattivazione lock cartella
  2902. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2903. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2904. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2905. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2906. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  2907. }
  2908. [self.tableView reloadData];
  2909. }
  2910. }
  2911. break;
  2912. default:
  2913. break;
  2914. }
  2915. }
  2916. - (void)comandoLockPassword
  2917. {
  2918. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2919. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2920. // se non è abilitato il Lock Passcode esci
  2921. if ([[CCUtility getBlockCode] length] == 0) {
  2922. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2923. [alertView show];
  2924. return;
  2925. }
  2926. // se è richiesta la disattivazione si chiede la password
  2927. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2928. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2929. viewController.delegate = self;
  2930. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2931. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2932. viewController.inputViewTitlePassword = YES;
  2933. if ([CCUtility getSimplyBlockCode]) {
  2934. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2935. viewController.passcodeInputView.maximumLength = 6;
  2936. } else {
  2937. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2938. viewController.passcodeInputView.maximumLength = 64;
  2939. }
  2940. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  2941. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2942. viewController.touchIDManager = touchIDManager;
  2943. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2944. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2945. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_ENCRYPTED;
  2946. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2947. [self presentViewController:navigationController animated:YES completion:nil];
  2948. return;
  2949. }
  2950. // ---------------- ACTIVATE PASSWORD
  2951. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2952. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2953. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2954. } else {
  2955. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  2956. }
  2957. }
  2958. #pragma mark -
  2959. #pragma --------------------------------------------------------------------------------------------
  2960. #pragma mark ===== Swipe Tablet -> menu =====
  2961. #pragma --------------------------------------------------------------------------------------------
  2962. // more
  2963. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2964. return NSLocalizedString(@"_more_", nil);
  2965. }
  2966. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2967. {
  2968. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2969. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2970. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder;
  2971. BOOL offlineFolder = NO;
  2972. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2973. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2974. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2975. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2976. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2977. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  2978. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2979. offlineFolder = YES;
  2980. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2981. if (_metadata.directory) {
  2982. // calcolo lockServerUrl
  2983. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  2984. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2985. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2986. }
  2987. /******************************************* AHKActionSheet *******************************************/
  2988. UIImage *iconHeader;
  2989. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  2990. actionSheet.animationDuration = 0.2;
  2991. actionSheet.blurRadius = 0.0f;
  2992. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  2993. actionSheet.buttonHeight = 50.0;
  2994. actionSheet.cancelButtonHeight = 50.0f;
  2995. actionSheet.separatorHeight = 5.0f;
  2996. actionSheet.automaticallyTintButtonImages = @(NO);
  2997. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_ENCRYPTED };
  2998. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:COLOR_GRAY };
  2999. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:COLOR_BRAND };
  3000. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:12], NSForegroundColorAttributeName:COLOR_GRAY };
  3001. actionSheet.separatorColor = COLOR_SEPARATOR_TABLE;
  3002. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3003. /******************************************* DIRECTORY *******************************************/
  3004. if (_metadata.directory) {
  3005. UIImage *iconHeader;
  3006. BOOL lockDirectory = NO;
  3007. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  3008. NSString *upDir = [CCUtility deletingLastPathComponentFromServerUrl:dirServerUrl];
  3009. NSString *homeDir = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl typeCloud:app.typeCloud];
  3010. // Directory bloccata ?
  3011. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3012. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3013. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3014. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud];
  3015. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3016. image: iconHeader
  3017. backgroundColor: COLOR_NAVBAR_IOS7
  3018. height: 50.0
  3019. type: AHKActionSheetButtonTypeDisabled
  3020. handler: nil
  3021. ];
  3022. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3023. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3024. image:[UIImage imageNamed:image_actionSheetRename]
  3025. backgroundColor:[UIColor whiteColor]
  3026. height: 50.0
  3027. type:AHKActionSheetButtonTypeDefault
  3028. handler:^(AHKActionSheet *as) {
  3029. // close swipe
  3030. [self setEditing:NO animated:YES];
  3031. //chiediamo il nome del file
  3032. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3033. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3034. alertView.tag = alertRename;
  3035. UITextField *textField = [alertView textFieldAtIndex:0];
  3036. textField.text = _metadata.fileNamePrint;
  3037. [alertView show];
  3038. }];
  3039. }
  3040. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3041. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3042. image:[UIImage imageNamed:image_actionSheetMove]
  3043. backgroundColor:[UIColor whiteColor]
  3044. height: 50.0
  3045. type:AHKActionSheetButtonTypeDefault
  3046. handler:^(AHKActionSheet *as) {
  3047. // close swipe
  3048. [self setEditing:NO animated:YES];
  3049. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3050. }];
  3051. }
  3052. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3053. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3054. image:[UIImage imageNamed:image_actionSheetCrypto]
  3055. backgroundColor:[UIColor whiteColor]
  3056. height: 50.0
  3057. type:AHKActionSheetButtonTypeEncrypted
  3058. handler:^(AHKActionSheet *as) {
  3059. // close swipe
  3060. [self setEditing:NO animated:YES];
  3061. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil afterDelay:0.1];
  3062. }];
  3063. }
  3064. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3065. [actionSheet addButtonWithTitle:titoloLock
  3066. image:[UIImage imageNamed:image_actionSheetLock]
  3067. backgroundColor:[UIColor whiteColor]
  3068. height: 50.0
  3069. type:AHKActionSheetButtonTypeEncrypted
  3070. handler:^(AHKActionSheet *as) {
  3071. // close swipe
  3072. [self setEditing:NO animated:YES];
  3073. [self performSelector:@selector(comandoLockPassword) withObject:nil afterDelay:0.1];
  3074. }];
  3075. }
  3076. if (_metadata.cryptated == NO && app.hasServerShareSupport && !lockDirectory) {
  3077. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3078. image:[UIImage imageNamed:image_actionSheetShare]
  3079. backgroundColor:[UIColor whiteColor]
  3080. height: 50.0
  3081. type:AHKActionSheetButtonTypeDefault
  3082. handler:^(AHKActionSheet *as) {
  3083. // close swipe
  3084. [self setEditing:NO animated:YES];
  3085. [self openWindowShare:_metadata];
  3086. }];
  3087. }
  3088. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3089. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3090. image:[UIImage imageNamed:image_folderphotocamera]
  3091. backgroundColor:[UIColor whiteColor]
  3092. height: 50.0
  3093. type:AHKActionSheetButtonTypeDefault
  3094. handler:^(AHKActionSheet *as) {
  3095. // close swipe
  3096. [self setEditing:NO animated:YES];
  3097. // Settings new folder Automatatic upload
  3098. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl typeCloud:app.typeCloud];
  3099. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3100. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl typeCloud:app.typeCloud activeAccount:app.activeAccount];
  3101. [CCCoreData clearDateReadDirectory:oldPath activeAccount:app.activeAccount];
  3102. if (app.activeAccount && app.activeUrl && app.activePhotosCameraUpload)
  3103. [app.activePhotosCameraUpload reloadDatasourceForced];
  3104. [self readFolderWithForced:YES];
  3105. }];
  3106. }
  3107. if (!lockDirectory && ([upDir isEqualToString:homeDir] || ![CCCoreData isOfflineDirectoryServerUrl:upDir activeAccount:app.activeAccount])) {
  3108. [actionSheet addButtonWithTitle:titleOfflineFolder
  3109. image:[UIImage imageNamed:image_actionSheetOffline]
  3110. backgroundColor:[UIColor whiteColor]
  3111. height: 50.0
  3112. type:AHKActionSheetButtonTypeDefault
  3113. handler:^(AHKActionSheet *as) {
  3114. // close swipe
  3115. [self setEditing:NO animated:YES];
  3116. if (offlineFolder == NO) {
  3117. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"",nil) message:NSLocalizedString(@"_offline_folder_confirm_",nil) delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3118. alertView.tag = alertOfflineFolder;
  3119. [alertView show];
  3120. } else {
  3121. // remove tag offline for all folder/subfolder/file
  3122. NSArray *directories = [CCCoreData getOfflineDirectoryActiveAccount:app.activeAccount];
  3123. for (TableDirectory *directory in directories)
  3124. if ([directory.serverUrl containsString:dirServerUrl]) {
  3125. [CCCoreData setOfflineDirectoryServerUrl:directory.serverUrl offline:NO activeAccount:app.activeAccount];
  3126. [CCCoreData removeOfflineAllFileFromServerUrl:directory.serverUrl activeAccount:app.activeAccount];
  3127. }
  3128. [self performSelector:@selector(reloadDatasource) withObject:nil];
  3129. }
  3130. }];
  3131. }
  3132. [actionSheet show];
  3133. }
  3134. /******************************************* FILE *******************************************/
  3135. if ([_metadata.type isEqualToString:metadataType_file] && !_metadata.directory) {
  3136. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3137. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3138. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3139. else
  3140. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3141. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3142. image: iconHeader
  3143. backgroundColor: COLOR_NAVBAR_IOS7
  3144. height: 50.0
  3145. type: AHKActionSheetButtonTypeDisabled
  3146. handler: nil
  3147. ];
  3148. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3149. image:[UIImage imageNamed:image_actionSheetRename]
  3150. backgroundColor:[UIColor whiteColor]
  3151. height: 50.0
  3152. type:AHKActionSheetButtonTypeDefault
  3153. handler:^(AHKActionSheet *as) {
  3154. // close swipe
  3155. [self setEditing:NO animated:YES];
  3156. //chiediamo il nome del file
  3157. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3158. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3159. alertView.tag = alertRename;
  3160. UITextField *textField = [alertView textFieldAtIndex:0];
  3161. textField.text = _metadata.fileNamePrint;
  3162. [alertView show];
  3163. }];
  3164. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3165. image:[UIImage imageNamed:image_actionSheetMove]
  3166. backgroundColor:[UIColor whiteColor]
  3167. height: 50.0
  3168. type:AHKActionSheetButtonTypeDefault
  3169. handler:^(AHKActionSheet *as) {
  3170. // close swipe
  3171. [self setEditing:NO animated:YES];
  3172. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3173. }];
  3174. [actionSheet addButtonWithTitle:NSLocalizedString(@"_reload_", nil)
  3175. image:[UIImage imageNamed:image_actionSheetReload]
  3176. backgroundColor:[UIColor whiteColor]
  3177. height: 50.0
  3178. type:AHKActionSheetButtonTypeDefault
  3179. handler:^(AHKActionSheet *as) {
  3180. // close swipe
  3181. [self setEditing:NO animated:YES];
  3182. [self performSelector:@selector(reloadFile:) withObject:_metadata afterDelay:0.1];
  3183. }];
  3184. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3185. image:[UIImage imageNamed:image_actionSheetOpenIn]
  3186. backgroundColor:[UIColor whiteColor]
  3187. height: 50.0
  3188. type:AHKActionSheetButtonTypeDefault
  3189. handler:^(AHKActionSheet *as) {
  3190. // close swipe
  3191. [self setEditing:NO animated:YES];
  3192. [self performSelector:@selector(openIn:) withObject:_metadata afterDelay:0.1];
  3193. }];
  3194. if (_metadata.cryptated == NO && app.hasServerShareSupport) {
  3195. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3196. image:[UIImage imageNamed:image_actionSheetShare]
  3197. backgroundColor:[UIColor whiteColor]
  3198. height: 50.0
  3199. type:AHKActionSheetButtonTypeDefault
  3200. handler:^(AHKActionSheet *as) {
  3201. // close swipe
  3202. [self setEditing:NO animated:YES];
  3203. [self openWindowShare:_metadata];
  3204. }];
  3205. }
  3206. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3207. image:[UIImage imageNamed:image_actionSheetCrypto]
  3208. backgroundColor:[UIColor whiteColor]
  3209. height: 50.0
  3210. type:AHKActionSheetButtonTypeEncrypted
  3211. handler:^(AHKActionSheet *as) {
  3212. // close swipe
  3213. [self setEditing:NO animated:YES];
  3214. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil afterDelay:0.1];
  3215. }];
  3216. if (![CCCoreData isOfflineDirectoryServerUrl:serverUrl activeAccount:app.activeAccount]) {
  3217. [actionSheet addButtonWithTitle:titoloOffline
  3218. image:[UIImage imageNamed:image_actionSheetOffline]
  3219. backgroundColor:[UIColor whiteColor]
  3220. height: 50.0
  3221. type:AHKActionSheetButtonTypeDefault
  3222. handler:^(AHKActionSheet *as) {
  3223. // close swipe
  3224. [self setEditing:NO animated:YES];
  3225. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) {
  3226. [self removeOffline:_metadata];
  3227. } else {
  3228. [self addOffline:_metadata];
  3229. }
  3230. }];
  3231. }
  3232. [actionSheet addButtonWithTitle:NSLocalizedString(@"_add_local_", nil)
  3233. image:[UIImage imageNamed:image_actionSheetLocal]
  3234. backgroundColor:[UIColor whiteColor]
  3235. height: 50.0
  3236. type:AHKActionSheetButtonTypeDefault
  3237. handler:^(AHKActionSheet *as) {
  3238. // close swipe
  3239. [self setEditing:NO animated:YES];
  3240. [self performSelector:@selector(addLocal:) withObject:_metadata afterDelay:0.1];
  3241. }];
  3242. [actionSheet show];
  3243. }
  3244. /******************************************* TEMPLATE *******************************************/
  3245. if ([_metadata.type isEqualToString:metadataType_model]) {
  3246. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3247. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3248. image: iconHeader
  3249. backgroundColor: COLOR_NAVBAR_IOS7
  3250. height: 50.0
  3251. type: AHKActionSheetButtonTypeDisabled
  3252. handler: nil
  3253. ];
  3254. if ([_metadata.model isEqualToString:@"note"]) {
  3255. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3256. image:[UIImage imageNamed:image_actionSheetRename]
  3257. backgroundColor:[UIColor whiteColor]
  3258. height: 50.0
  3259. type:AHKActionSheetButtonTypeDefault
  3260. handler:^(AHKActionSheet *as) {
  3261. // close swipe
  3262. [self setEditing:NO animated:YES];
  3263. //chiediamo il nome del file
  3264. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3265. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3266. alertView.tag = alertRename;
  3267. UITextField *textField = [alertView textFieldAtIndex:0];
  3268. textField.text = _metadata.fileNamePrint;
  3269. [alertView show];
  3270. }];
  3271. }
  3272. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3273. image:[UIImage imageNamed:image_actionSheetMove]
  3274. backgroundColor:[UIColor whiteColor]
  3275. height: 50.0
  3276. type:AHKActionSheetButtonTypeDefault
  3277. handler:^(AHKActionSheet *as) {
  3278. // close swipe
  3279. [self setEditing:NO animated:YES];
  3280. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3281. }];
  3282. [actionSheet addButtonWithTitle:titoloOffline
  3283. image:[UIImage imageNamed:image_actionSheetOffline]
  3284. backgroundColor:[UIColor whiteColor]
  3285. height: 50.0
  3286. type:AHKActionSheetButtonTypeDefault
  3287. handler:^(AHKActionSheet *as) {
  3288. // close swipe
  3289. [self setEditing:NO animated:YES];
  3290. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount])
  3291. [self removeOffline:_metadata];
  3292. else
  3293. [self addOffline:_metadata];
  3294. }];
  3295. [actionSheet addButtonWithTitle:NSLocalizedString(@"_add_local_", nil)
  3296. image:[UIImage imageNamed:image_actionSheetLocal]
  3297. backgroundColor:[UIColor whiteColor]
  3298. height: 50.0
  3299. type:AHKActionSheetButtonTypeDefault
  3300. handler:^(AHKActionSheet *as) {
  3301. // close swipe
  3302. [self setEditing:NO animated:YES];
  3303. [self performSelector:@selector(addLocal:) withObject:_metadata afterDelay:0.1];
  3304. }];
  3305. [actionSheet show];
  3306. }
  3307. }
  3308. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3309. {
  3310. return NSLocalizedString(@"_delete_", nil);
  3311. }
  3312. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3313. {
  3314. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3315. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3316. else return YES;
  3317. }
  3318. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3319. {
  3320. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3321. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3322. else return UITableViewCellEditingStyleDelete;
  3323. }
  3324. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3325. {
  3326. BOOL lockDirectory = NO;
  3327. // Directory locked ?
  3328. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addServerUrl:_metadata.fileNameData];
  3329. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3330. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3331. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  3332. return;
  3333. }
  3334. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3335. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3336. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3337. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3338. style:UIAlertActionStyleDestructive
  3339. handler:^(UIAlertAction *action) {
  3340. [self performSelector:@selector(deleteFile) withObject:nil afterDelay:0.1];
  3341. }]];
  3342. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3343. style:UIAlertActionStyleCancel
  3344. handler:^(UIAlertAction *action) {
  3345. [alertController dismissViewControllerAnimated:YES completion:nil];
  3346. }]];
  3347. alertController.popoverPresentationController.sourceView = self.view;
  3348. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3349. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3350. [alertController.view layoutIfNeeded];
  3351. [self presentViewController:alertController animated:YES completion:nil];
  3352. }
  3353. }
  3354. #pragma --------------------------------------------------------------------------------------------
  3355. #pragma mark - ==== Datasource ====
  3356. #pragma --------------------------------------------------------------------------------------------
  3357. - (void)clearDateReadDataSource:(NSNotification *)notification
  3358. {
  3359. _dateReadDataSource = Nil;
  3360. }
  3361. - (void)reloadDatasource
  3362. {
  3363. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3364. }
  3365. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3366. {
  3367. if (app.activeAccount == nil || app.activeUrl == nil || serverUrl == nil)
  3368. return;
  3369. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3370. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3371. if ([selector isEqualToString:selectorDownloadOffline]) {
  3372. [app.controlCenter reloadDatasource];
  3373. } else {
  3374. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3375. if (main) {
  3376. [main reloadDatasource];
  3377. } else {
  3378. [self tableViewReload];
  3379. [app.controlCenter reloadDatasource];
  3380. }
  3381. }
  3382. return;
  3383. }
  3384. // Offline folder ?
  3385. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3386. [app.controlCenter reloadDatasource];
  3387. // Settaggio variabili per le ottimizzazioni
  3388. _directoryGroupBy = [CCUtility getGroupBySettings];
  3389. _directoryOrder = [CCUtility getOrderSettings];
  3390. // Controllo data lettura Data Source
  3391. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3392. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3393. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3394. _dateReadDataSource = [NSDate date];
  3395. // Data Source
  3396. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3397. _sectionDataSource = [CCSection creataDataSourseSectionTableMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3398. } else {
  3399. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3400. }
  3401. [self tableViewReload];
  3402. [self setTitleBackgroundTableView];
  3403. [app updateApplicationIconBadgeNumber];
  3404. }
  3405. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3406. {
  3407. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3408. if (selectedRows.count > 0) {
  3409. for (NSIndexPath *selectionIndex in selectedRows) {
  3410. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3411. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3412. [metadatas addObject:metadata];
  3413. }
  3414. }
  3415. return metadatas;
  3416. }
  3417. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3418. {
  3419. NSInteger section = indexPath.section + 1;
  3420. NSInteger row = indexPath.row + 1;
  3421. NSInteger totSections =[_sectionDataSource.sections count] ;
  3422. if ((totSections < section) || (section > totSections)) {
  3423. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3424. return nil;
  3425. }
  3426. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3427. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3428. if (fileIDs) {
  3429. NSInteger totRows =[fileIDs count] ;
  3430. if ((totRows < row) || (row > totRows)) {
  3431. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3432. return nil;
  3433. }
  3434. } else {
  3435. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3436. return nil;
  3437. }
  3438. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3439. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3440. }
  3441. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3442. {
  3443. NSInteger totSections =[_sectionDataSource.sections count] ;
  3444. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3445. #if DEBUG
  3446. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3447. [alertView show];
  3448. #endif
  3449. return nil;
  3450. }
  3451. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3452. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3453. }
  3454. #pragma --------------------------------------------------------------------------------------------
  3455. #pragma mark - ==== Table ====
  3456. #pragma --------------------------------------------------------------------------------------------
  3457. - (void)tableViewSelect:(BOOL)edit
  3458. {
  3459. // chiudiamo eventuali swipe aperti
  3460. if (edit) [self.tableView setEditing:NO animated:NO];
  3461. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3462. [self.tableView setEditing:edit animated:YES];
  3463. _isSelectedMode = edit;
  3464. if (edit)
  3465. [self setUINavigationBarSelected];
  3466. else
  3467. [self setUINavigationBarDefault];
  3468. [self setTitleNOAnimation];
  3469. }
  3470. - (void)tableViewReload
  3471. {
  3472. // ricordiamoci le row selezionate
  3473. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3474. [self.tableView reloadData];
  3475. for (NSIndexPath *path in indexPaths)
  3476. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3477. [self setTableViewFooter];
  3478. if (self.tableView.editing)
  3479. [self setTitleNOAnimation];
  3480. }
  3481. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3482. {
  3483. return 60;
  3484. }
  3485. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3486. {
  3487. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3488. }
  3489. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3490. {
  3491. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3492. }
  3493. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3494. {
  3495. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3496. NSString *sectionTitle = [sections objectAtIndex:section];
  3497. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3498. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3499. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3500. return 20.f;
  3501. }
  3502. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3503. {
  3504. float shift;
  3505. UIVisualEffectView *visualEffectView;
  3506. // Titolo
  3507. NSString *titleSection;
  3508. // Controllo
  3509. if ([_sectionDataSource.sections count] == 0)
  3510. return nil;
  3511. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3512. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3513. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3514. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3515. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3516. else titleSection = NSLocalizedString(titleSection,nil);
  3517. // Formato titolo
  3518. NSString *currentDevice = [CCUtility currentDevice];
  3519. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3520. visualEffectView = [[UIVisualEffectView alloc] init];
  3521. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  3522. } else {
  3523. UIVisualEffect *blurEffect;
  3524. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3525. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3526. visualEffectView.backgroundColor = COLOR_GROUPBY_BAR;
  3527. }
  3528. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3529. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3530. else shift = - 20;
  3531. } else shift = - 10;
  3532. // Title
  3533. UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3534. titleLabel.backgroundColor=[UIColor clearColor];
  3535. titleLabel.textColor = COLOR_GRAY;
  3536. titleLabel.font = [UIFont systemFontOfSize:12];
  3537. titleLabel.textAlignment = NSTextAlignmentLeft;
  3538. titleLabel.text = titleSection;
  3539. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3540. [visualEffectView addSubview:titleLabel];
  3541. // Elements
  3542. UILabel *elementLabel=[[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3543. elementLabel.backgroundColor=[UIColor clearColor];
  3544. elementLabel.textColor = COLOR_GRAY;
  3545. elementLabel.font = [UIFont systemFontOfSize:12];
  3546. elementLabel.textAlignment = NSTextAlignmentRight;
  3547. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3548. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3549. NSUInteger rowsCount = [metadatas count];
  3550. if (rowsCount == 0) return nil;
  3551. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3552. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3553. [visualEffectView addSubview:elementLabel];
  3554. return visualEffectView;
  3555. }
  3556. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3557. {
  3558. return [_sectionDataSource.sections indexOfObject:title];
  3559. }
  3560. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3561. {
  3562. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3563. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3564. else
  3565. return nil;
  3566. }
  3567. /*
  3568. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3569. {
  3570. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3571. }
  3572. }
  3573. */
  3574. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3575. {
  3576. NSString *typeCell;
  3577. NSString *dataFile;
  3578. NSString *lunghezzaFile;
  3579. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3580. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3581. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3582. else typeCell = @"CellMainTransfer";
  3583. if (!metadata)
  3584. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3585. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3586. // separator
  3587. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3588. // change color selection
  3589. UIView *selectionColor = [[UIView alloc] init];
  3590. selectionColor.backgroundColor = COLOR_SELECT_BACKGROUND;
  3591. cell.selectedBackgroundView = selectionColor;
  3592. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3593. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = COLOR_TRANSFER_BACKGROUND;
  3594. // ----------------------------------------------------------------------------------------------------------
  3595. // DEFAULT
  3596. // ----------------------------------------------------------------------------------------------------------
  3597. cell.fileImageView.image = nil;
  3598. cell.statusImageView.image = nil;
  3599. cell.offlineImageView.image = nil;
  3600. cell.synchronizedImageView.image = nil;
  3601. cell.sharedImageView.image = nil;
  3602. cell.labelTitle.enabled = YES;
  3603. cell.labelTitle.text = @"";
  3604. cell.labelInfoFile.enabled = YES;
  3605. cell.labelInfoFile.text = @"";
  3606. cell.progressView.progress = 0.0;
  3607. cell.progressView.hidden = YES;
  3608. cell.cancelTaskButton.hidden = YES;
  3609. cell.reloadTaskButton.hidden = YES;
  3610. cell.stopTaskButton.hidden = YES;
  3611. // colori e font
  3612. if (metadata.cryptated) {
  3613. cell.labelTitle.textColor = COLOR_ENCRYPTED;
  3614. //nameLabel.font = RalewayLight(13.0f);
  3615. cell.labelInfoFile.textColor = [UIColor blackColor];
  3616. //detailLabel.font = RalewayLight(9.0f);
  3617. } else {
  3618. cell.labelTitle.textColor = COLOR_CLEAR;
  3619. //nameLabel.font = RalewayLight(13.0f);
  3620. cell.labelInfoFile.textColor = [UIColor blackColor];
  3621. //detailLabel.font = RalewayLight(9.0f);
  3622. }
  3623. // ----------------------------------------------------------------------------------------------------------
  3624. // File Name & Folder
  3625. // ----------------------------------------------------------------------------------------------------------
  3626. // nome del file
  3627. cell.labelTitle.text = metadata.fileNamePrint;
  3628. // è una directory
  3629. if (metadata.directory) {
  3630. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3631. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3632. lunghezzaFile = @" ";
  3633. // ----------------------------------------------------------------------------------------------------------
  3634. // Offline Folder
  3635. // ----------------------------------------------------------------------------------------------------------
  3636. NSString *directoryServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:metadata.fileNameData];
  3637. BOOL isOfflineDirectory = [CCCoreData isOfflineDirectoryServerUrl:directoryServerUrl activeAccount:app.activeAccount];
  3638. // Verify Offline
  3639. if (_isOfflineServerUrl == YES && isOfflineDirectory == NO) {
  3640. [CCCoreData setOfflineDirectoryServerUrl:directoryServerUrl offline:YES activeAccount:app.activeAccount];
  3641. isOfflineDirectory = YES;
  3642. }
  3643. if (isOfflineDirectory) {
  3644. // Image Offline
  3645. if (metadata.cryptated) cell.offlineImageView.image = [UIImage imageNamed:image_offlinecrypto];
  3646. else cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3647. // Animation synchronized gif
  3648. if ([[CCOfflineFileFolder sharedOfflineFileFolder] offlineFolderAnimationDirectory:[[NSArray alloc] initWithObjects:directoryServerUrl, nil] callViewController:NO]) {
  3649. NSURL *myURL;
  3650. if (metadata.cryptated) myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3651. else myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3652. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  3653. }
  3654. }
  3655. } else {
  3656. // è un file
  3657. dataFile = [CCUtility dateDiff:metadata.date];
  3658. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3659. // Plist ancora da scaricare
  3660. if (metadata.cryptated && [metadata.title length] == 0) {
  3661. dataFile = @" ";
  3662. lunghezzaFile = @" ";
  3663. }
  3664. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3665. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3666. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3667. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3668. if ([metadata.type isEqualToString:metadataType_model] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3669. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3670. if ([metadata.type isEqualToString:metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3671. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3672. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3673. else
  3674. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3675. }
  3676. // Plist ancora da scaricare
  3677. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3678. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3679. cell.accessoryType = UITableViewCellAccessoryNone;
  3680. }
  3681. // ----------------------------------------------------------------------------------------------------------
  3682. // File Image View
  3683. // ----------------------------------------------------------------------------------------------------------
  3684. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3685. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3686. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3687. if (cell.fileImageView.image == nil) {
  3688. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3689. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3690. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3691. dispatch_async(dispatch_get_main_queue(), ^{
  3692. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3693. if (cell)
  3694. cell.fileImageView.image = image;
  3695. });
  3696. });
  3697. }
  3698. } else {
  3699. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3700. if (metadata.thumbnailExists)
  3701. [self downloadThumbnail:metadata];
  3702. }
  3703. // ----------------------------------------------------------------------------------------------------------
  3704. // Image Status cyptated & Lock Passcode
  3705. // ----------------------------------------------------------------------------------------------------------
  3706. // File Cyptated
  3707. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString:metadataType_model] == NO) {
  3708. cell.statusImageView.image = [UIImage imageNamed:image_lock];
  3709. }
  3710. // Directory con passcode lock attivato
  3711. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:metadata.fileNameData];
  3712. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length])) cell.statusImageView.image = [UIImage imageNamed:image_passcode];
  3713. // ----------------------------------------------------------------------------------------------------------
  3714. // Offline
  3715. // ----------------------------------------------------------------------------------------------------------
  3716. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3717. // Verify Offline
  3718. if(_isOfflineServerUrl || isOfflineFile) {
  3719. isOfflineFile = YES;
  3720. }
  3721. if (isOfflineFile) {
  3722. if (metadata.cryptated) cell.offlineImageView.image = [UIImage imageNamed:image_offlinecrypto];
  3723. else cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3724. }
  3725. // ----------------------------------------------------------------------------------------------------------
  3726. // Share
  3727. // ----------------------------------------------------------------------------------------------------------
  3728. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3729. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3730. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3731. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3732. // Aggiungiamo il Tap per le shared
  3733. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3734. if (isShare) {
  3735. cell.sharedImageView.image = [UIImage imageNamed:image_shareConnect];
  3736. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3737. [tap setNumberOfTapsRequired:1];
  3738. cell.sharedImageView.userInteractionEnabled = YES;
  3739. [cell.sharedImageView addGestureRecognizer:tap];
  3740. }
  3741. if (isMounted) {
  3742. cell.sharedImageView.image = [UIImage imageNamed:image_shareMounted];
  3743. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3744. [tap setNumberOfTapsRequired:1];
  3745. cell.sharedImageView.userInteractionEnabled = YES;
  3746. [cell.sharedImageView addGestureRecognizer:tap];
  3747. }
  3748. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3749. if ([shareLink length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareLink];
  3750. if ([shareUserAndGroup length] > 0) cell.sharedImageView.image = [UIImage imageNamed:image_shareUser];
  3751. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3752. [tap setNumberOfTapsRequired:1];
  3753. cell.sharedImageView.userInteractionEnabled = YES;
  3754. [cell.sharedImageView addGestureRecognizer:tap];
  3755. }
  3756. } else {
  3757. cell.sharedImageView.userInteractionEnabled = NO;
  3758. }
  3759. // ----------------------------------------------------------------------------------------------------------
  3760. // downloadFile
  3761. // ----------------------------------------------------------------------------------------------------------
  3762. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"download"].location != NSNotFound) {
  3763. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusdownloadcrypto];
  3764. else cell.statusImageView.image = [UIImage imageNamed:image_statusdownload];
  3765. // sessionTaskIdentifier : RELOAD + STOP
  3766. if (metadata.sessionTaskIdentifier != taskIdentifierDone) {
  3767. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3768. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3769. cell.cancelTaskButton.hidden = NO;
  3770. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3771. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3772. cell.reloadTaskButton.hidden = NO;
  3773. }
  3774. // sessionTaskIdentifierPlist : RELOAD
  3775. if (metadata.sessionTaskIdentifierPlist != taskIdentifierDone) {
  3776. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3777. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3778. cell.reloadTaskButton.hidden = NO;
  3779. }
  3780. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3781. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3782. if (progress > 0) {
  3783. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_ENCRYPTED;
  3784. else cell.progressView.progressTintColor = COLOR_CLEAR;
  3785. cell.progressView.progress = progress;
  3786. cell.progressView.hidden = NO;
  3787. }
  3788. // ----------------------------------------------------------------------------------------------------------
  3789. // downloadFile Error
  3790. // ----------------------------------------------------------------------------------------------------------
  3791. if (metadata.sessionTaskIdentifier == taskIdentifierError || metadata.sessionTaskIdentifierPlist == taskIdentifierError) {
  3792. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3793. if ([metadata.sessionError length] == 0)
  3794. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3795. else
  3796. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3797. }
  3798. }
  3799. // ----------------------------------------------------------------------------------------------------------
  3800. // uploadFile
  3801. // ----------------------------------------------------------------------------------------------------------
  3802. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3803. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusuploadcrypto];
  3804. else cell.statusImageView.image = [UIImage imageNamed:image_statusupload];
  3805. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetaskcrypto] forState:UIControlStateNormal];
  3806. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetask] forState:UIControlStateNormal];
  3807. cell.cancelTaskButton.hidden = NO;
  3808. if (metadata.sessionTaskIdentifier == taskIdentifierStop) {
  3809. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3810. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3811. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusstopcrypto];
  3812. else cell.statusImageView.image = [UIImage imageNamed:image_statusstop];
  3813. cell.reloadTaskButton.hidden = NO;
  3814. cell.stopTaskButton.hidden = YES;
  3815. } else {
  3816. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3817. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3818. cell.stopTaskButton.hidden = NO;
  3819. cell.reloadTaskButton.hidden = YES;
  3820. }
  3821. // se non c'è una preview in bianconero metti l'immagine di default
  3822. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3823. cell.fileImageView.image = [UIImage imageNamed:image_uploaddisable];
  3824. cell.labelTitle.enabled = NO;
  3825. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3826. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3827. if (progress > 0) {
  3828. if (metadata.cryptated) cell.progressView.progressTintColor = COLOR_ENCRYPTED;
  3829. else cell.progressView.progressTintColor = COLOR_CLEAR;
  3830. cell.progressView.progress = progress;
  3831. cell.progressView.hidden = NO;
  3832. }
  3833. // ----------------------------------------------------------------------------------------------------------
  3834. // uploadFileError
  3835. // ----------------------------------------------------------------------------------------------------------
  3836. if (metadata.sessionTaskIdentifier == taskIdentifierError || metadata.sessionTaskIdentifierPlist == taskIdentifierError) {
  3837. cell.labelTitle.enabled = NO;
  3838. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3839. if ([metadata.sessionError length] == 0)
  3840. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3841. else
  3842. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3843. }
  3844. }
  3845. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3846. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3847. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3848. return cell;
  3849. }
  3850. - (void)setTableViewFooter
  3851. {
  3852. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3853. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3854. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3855. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3856. UIFont *appFont = [UIFont systemFontOfSize:12];
  3857. footerLabel.font = appFont;
  3858. footerLabel.textColor = [UIColor grayColor];
  3859. footerLabel.backgroundColor = [UIColor clearColor];
  3860. footerLabel.textAlignment = NSTextAlignmentCenter;
  3861. NSString *folders;
  3862. NSString *files;
  3863. NSString *footerText;
  3864. if (_sectionDataSource.directories > 1) {
  3865. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3866. } else if (_sectionDataSource.directories == 1){
  3867. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3868. } else {
  3869. folders = @"";
  3870. }
  3871. if (_sectionDataSource.files > 1) {
  3872. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3873. } else if (_sectionDataSource.files == 1){
  3874. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3875. } else {
  3876. files = @"";
  3877. }
  3878. if ([folders isEqualToString:@""]) {
  3879. footerText = files;
  3880. } else if ([files isEqualToString:@""]) {
  3881. footerText = folders;
  3882. } else {
  3883. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3884. }
  3885. footerLabel.text = footerText;
  3886. [footerView addSubview:footerLabel];
  3887. [self.tableView setTableFooterView:footerView];
  3888. }
  3889. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3890. {
  3891. NSString *textMessage;
  3892. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3893. // se non può essere selezionata deseleziona
  3894. if ([cell isEditing] == NO)
  3895. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3896. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3897. if (self.tableView.editing) {
  3898. [self setTitleNOAnimation];
  3899. return;
  3900. }
  3901. // test crash
  3902. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3903. if (indexPath.row >= [metadatas count]) return;
  3904. // settiamo il record file.
  3905. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3906. //
  3907. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3908. // se è in corso una sessione
  3909. if ([_metadata.session length] > 0) return;
  3910. if (_metadata.errorPasscode) {
  3911. // se UUID è nil lo sta ancora caricando quindi esci
  3912. if (!_metadata.uuid) return;
  3913. // esiste un hint ??
  3914. CCCrypto *crypto = [[CCCrypto alloc] init];
  3915. NSString *hint = [crypto getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3916. // qui !! la richiesta della nuova passcode
  3917. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3918. // stesso UUID ... la password è stata modificata !!!!!!
  3919. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3920. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3921. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3922. [alertView show];
  3923. } else {
  3924. // UUID diverso.
  3925. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3926. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3927. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3928. [alertView show];
  3929. }
  3930. // chiediamo la passcode e ricarichiamo tutto.
  3931. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3932. viewController.delegate = self;
  3933. viewController.fromType = CCBKPasscodeFromPasscode;
  3934. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3935. viewController.passcodeInputView.maximumLength = 64;
  3936. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3937. viewController.inputViewTitlePassword = NO;
  3938. viewController.title = _brand_;
  3939. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3940. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_ENCRYPTED;
  3941. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3942. [self presentViewController:navigationController animated:YES completion:nil];
  3943. }
  3944. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3945. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3946. NSString* selector;
  3947. if ([_metadata.type isEqualToString:metadataType_model]) selector = selectorLoadModelView;
  3948. else selector = selectorLoadPlist;
  3949. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  3950. return;
  3951. }
  3952. // se il plist è caricato ed è un modello aprilo
  3953. if ([_metadata.type isEqualToString:metadataType_model]) [self openModel:_metadata.model isNew:false];
  3954. // file
  3955. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString:metadataType_file]) {
  3956. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3957. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3958. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3959. } else {
  3960. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:self];
  3961. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3962. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3963. }
  3964. }
  3965. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3966. }
  3967. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3968. {
  3969. [self setTitleNOAnimation];
  3970. }
  3971. #pragma --------------------------------------------------------------------------------------------
  3972. #pragma mark ===== Offline Folder Cell =====
  3973. #pragma --------------------------------------------------------------------------------------------
  3974. - (void)offlineFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3975. {
  3976. BOOL cryptated = NO;
  3977. CCCellMain *cell;
  3978. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3979. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3980. if (recordMetadata.directory == NO)
  3981. continue;
  3982. if ([[CCUtility stringAppendServerUrl:_serverUrl addServerUrl:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3983. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3984. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3985. cryptated = recordMetadata.cryptated;
  3986. break;
  3987. }
  3988. }
  3989. if (!cell)
  3990. return;
  3991. if (animation) {
  3992. NSURL *myURL;
  3993. if (cryptated)
  3994. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  3995. else
  3996. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  3997. cell.synchronizedImageView.image = [UIImage animatedImageWithAnimatedGIFURL:myURL];
  3998. } else {
  3999. cell.synchronizedImageView.image = nil;
  4000. }
  4001. }
  4002. #pragma --------------------------------------------------------------------------------------------
  4003. #pragma mark ===== Navigation ====
  4004. #pragma --------------------------------------------------------------------------------------------
  4005. - (BOOL)shouldPerformSegue:(NSString *)serverUrl
  4006. {
  4007. // if background return
  4008. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4009. // se non siamo in primo piano o se non siamo nella stessa directory esci
  4010. if (self.view.window == NO || ([serverUrl isEqualToString:_serverUrl] == NO && serverUrl))
  4011. return NO;
  4012. // Collapsed ma siamo già in detail esci
  4013. if (self.splitViewController.isCollapsed)
  4014. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4015. // Video in esecuzione esci
  4016. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4017. return YES;
  4018. }
  4019. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4020. {
  4021. id viewController = segue.destinationViewController;
  4022. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4023. UINavigationController *nav = viewController;
  4024. _detailViewController = (CCDetail *)nav.topViewController;
  4025. } else {
  4026. _detailViewController = segue.destinationViewController;
  4027. }
  4028. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  4029. for (NSString *fileID in _sectionDataSource.allFileID) {
  4030. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4031. if ([metadata.typeFile isEqualToString:metadataTypeFile_image] || [metadata.typeFile isEqualToString:metadataTypeFile_video])
  4032. [allRecordsDataSourceImagesVideos addObject:metadata];
  4033. }
  4034. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4035. _detailViewController.metadataDetail = _metadataSegue;
  4036. _detailViewController.dateFilterQuery = nil;
  4037. _detailViewController.isCameraUpload = NO;
  4038. [_detailViewController setTitle:_metadata.fileNamePrint];
  4039. }
  4040. // can i go to next viewcontroller
  4041. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4042. {
  4043. NSString *nomeDir;
  4044. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4045. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4046. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:_metadata.fileNameData];
  4047. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4048. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4049. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4050. viewController.delegate = self;
  4051. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4052. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4053. viewController.inputViewTitlePassword = YES;
  4054. if ([CCUtility getSimplyBlockCode]) {
  4055. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4056. viewController.passcodeInputView.maximumLength = 6;
  4057. } else {
  4058. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4059. viewController.passcodeInputView.maximumLength = 64;
  4060. }
  4061. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:BKPasscodeKeychainServiceName];
  4062. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4063. viewController.touchIDManager = touchIDManager;
  4064. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4065. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4066. viewController.navigationItem.leftBarButtonItem.tintColor = COLOR_ENCRYPTED;
  4067. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4068. [self presentViewController:navController animated:YES completion:nil];
  4069. return;
  4070. }
  4071. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4072. else nomeDir = _metadata.fileName;
  4073. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addServerUrl:nomeDir];
  4074. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4075. if (viewController.isViewLoaded == false) {
  4076. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4077. viewController.isFolderEncrypted = _metadata.cryptated;
  4078. viewController.serverUrl = serverUrlPush;
  4079. viewController.titleMain = _metadata.fileNamePrint;
  4080. viewController.textBackButton = _titleMain;
  4081. // save self
  4082. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4083. }
  4084. [self.navigationController pushViewController:viewController animated:YES];
  4085. }
  4086. }
  4087. @end