CCMain.m 250 KB

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